﻿Imports System.Data.OleDb
Imports System.Data.Common
Namespace QuanLyKhachHang
    Public Class frmHopDong
        Inherits DevComponents.DotNetBar.Office2007Form
        Private MaHopDong As String
        Private dtSanPhamHD As New DataTable
        Private IdDonHangBan_Edit As Integer = 0
        Private IsLoaded As Boolean = False
        Private IsEdit As Boolean = False
        Private isFinished As Boolean = False
        Private RowEditIndex As Integer
        Private IDKhachHang_Max As Integer
        Private ReportType As Integer = 0
        Private IDKhachHang_Edit As Integer = 0
        Private cm As New Common
        Private aMaSanPham As New AutoCompleteStringCollection
        Private aMaKhachHang As New AutoCompleteStringCollection
        Private IndexCurrentMonth As Integer = 0
        Private DaTruKho As Boolean = False
        Private EditMode As Integer '=1 -->ChinhSua --> =2-->KeThuaDonHang
        Private Sub frmHopDong_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            '-------------Load Data--------------
            Try
                comboTien_Load()
                'Load So Hoa Don Tang Them 1
                AutoComplete()
                AutoComplete_MaKhachHang()
                TaoSoHoaDon()
                ''Grid Mục Trừ Hóa Đơn
                GiamTruHoaDon()
                ''Combox Loại Sản Phẩm
                LoaiSanPham_Load()
                NhanVienTiepThi_Load()
                ' ''SanPham_Load()
                ' ''MaHopDong = PhatSinhMaHopDong()
                ''NguyenLieu_Load()
                ''ThongTinSanPham_Load()
                'dtSanPhamHD = CreateSanPhamHopDong()
                ''Tạo đơn hàng có 15 dòng  admin 123
                InitOrder()
                GenerateOrderNumber()
                ' ''load Tab 2
                DisableControl()
                dtpTheoNgay.Enabled = True
                DisableTiepThi()
                cbxNhanVienTT.Enabled = True
                Nam_Load()
                Thang_Load()
                'Report_TheoNgay()
                ''Phân quyền Form
                Dim aPermission(4) As Boolean
                aPermission = PhanQuyenForm("MenuBanHang", frmMain.UserId)
                cmdLuu.Enabled = aPermission(0)
                cmdEdit.Enabled = aPermission(1)
                cmdAproved.Enabled = aPermission(1)
                cmdDelete.Enabled = aPermission(2)
                cmdPrint.Enabled = aPermission(3)
                ''


                dgvSanPhamHopdong_Tab1.ClearSelection()
                txtTenKhachHang.Focus()
                ''


            Catch ex As Exception
                ShowError(ex)
            End Try
        End Sub
        'Load Tien Te
        Private Sub comboTien_Load()
            Try
                Dim Tien As New List(Of String)
                Tien.Add("VND")
                Tien.Add("USD")
                Tien.Add("SGD")
                comboTien.DataSource = Tien
                comboTien.SelectedIndex = 0
                'set index
            Catch ex As Exception

            End Try
        End Sub
        Public Sub AutoComplete()
            Try
                'Auto Complete 
                Dim dbConn As New OleDb.OleDbConnection
                Dim dataAccess As New DataAccess
                Dim dtProductDetail As New DataTable
                Dim query As String = "Select MaSanPham From SanPham Where Xoa=0"
                Dim adapter As OleDb.OleDbDataAdapter
                dataAccess.ConnectDatabase_DBAccess(dbConn)
                adapter = New OleDb.OleDbDataAdapter(query, dbConn)
                adapter.Fill(dtProductDetail)
                dbConn.Close()
                aMaSanPham = New AutoCompleteStringCollection
                For i As Integer = 0 To dtProductDetail.Rows.Count - 1
                    aMaSanPham.Add(dtProductDetail.Rows(i)("MaSanPham"))
                Next
            Catch ex As Exception

            End Try
        End Sub
        Public Sub AutoComplete_MaKhachHang()
            Try
                'Auto Complete 
                Dim dbConn As New OleDb.OleDbConnection
                Dim dataAccess As New DataAccess
                Dim dtCustomerInfo As New DataTable
                Dim query As String = "Select CodeKhachHang From DanhMucKhachHang Where Xoa=0"
                Dim adapter As OleDb.OleDbDataAdapter
                dataAccess.ConnectDatabase_DBAccess(dbConn)
                adapter = New OleDb.OleDbDataAdapter(query, dbConn)
                adapter.Fill(dtCustomerInfo)
                dbConn.Close()
                aMaKhachHang = New AutoCompleteStringCollection
                For i As Integer = 0 To dtCustomerInfo.Rows.Count - 1
                    aMaKhachHang.Add(dtCustomerInfo.Rows(i)("CodeKhachHang"))
                Next
                txtMaKhachHang.AutoCompleteMode = AutoCompleteMode.SuggestAppend
                txtMaKhachHang.AutoCompleteSource = AutoCompleteSource.CustomSource
                txtMaKhachHang.AutoCompleteCustomSource = aMaKhachHang
            Catch ex As Exception

            End Try
        End Sub
#Region "Tab 1"
#Region "Load Data"
        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Load Danh Mục Sản Phẩm
        ''' </summary>
        ''' <remarks>
        ''' 
        ''' </remarks>
        ''' <history>
        '''   [lamtn] 19/02/2011  Created
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Public Sub SanPham_Load(ByVal TenSanPham As String)
            Dim dbConn As New OleDb.OleDbConnection
            Dim dataAccess As New DataAccess
            Dim dsSanPham As New DataSet
            Dim dtSanPham As New DataTable
            Dim query As String = "Select *,0 As [Type] from SanPham_Search Where MaSanPham Like N'" & TenSanPham & "%' Order By TenSanPham"
            Dim adapter As OleDb.OleDbDataAdapter
            dataAccess.ConnectDatabase_DBAccess(dbConn)
            adapter = New OleDb.OleDbDataAdapter(query, dbConn)
            adapter.Fill(dsSanPham)
            dbConn.Close()
            dtSanPham = dsSanPham.Tables(0)
            'dgvSanPham.AutoGenerateColumns = False

            'dgvSanPham.DataSource = dtSanPham
            Dim cellEdit As DataGridViewCell
            cellEdit = dgvSanPhamHopdong_Tab1.CurrentRow.Cells(0)
            dgvSanPhamHopdong_Tab1.CurrentCell = cellEdit
            dgvSanPhamHopdong_Tab1.CurrentCell.Selected = True
        End Sub
        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Load Danh Mục Sản Phẩm Theo Khach Hang
        ''' </summary>
        ''' <remarks>
        ''' 
        ''' </remarks>
        ''' <history>
        '''   [lamtn] 19/02/2011  Created
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Public Sub SanPhamTheoKhachHang_Load(ByVal TenSanPham As String, ByVal KhachHangId As String)
            'If Not cbxSearchSupport.Checked Then
            '    Exit Sub
            'End If
            'Dim dbConn As New OleDb.OleDbConnection
            'Dim dataAccess As New DataAccess
            'Dim dsSanPham As New DataSet
            'Dim dtSanPham As New DataTable
            'Dim query As String = "Select *,0 As [Type] from SanPham_Search Where MaSanPham Like N'" & TenSanPham & "%' Order By TenSanPham"
            'Dim adapter As OleDb.OleDbDataAdapter
            'dataAccess.ConnectDatabase_DBAccess(dbConn)
            'adapter = New OleDb.OleDbDataAdapter(query, dbConn)
            'adapter.Fill(dsSanPham)

            'dtSanPham = dsSanPham.Tables(0)
            'dgvSanPham.AutoGenerateColumns = False
            'Dim dtSanPhamTheoKhachHang As New DataTable
            'query = "Select NG.IDSanPham,SPS.MaLoai,SPS.TenLoai,SPS.MaSanPham,SPS.TenSanPham,SPS.TenDonViTinh,NG.DonGiaII AS DonGia,SPS.SoLuongTon,1 As [Type] From SanPhamNhieuGia As NG" & _
            '        " Left Outer Join SanPham_Search As SPS ON NG.IDSanPham=SPS.IDSanPham" & _
            '        " Where NG.Xoa = 0 And NG.IDKhachHang =" & KhachHangId & " And MaSanPham Like N'" & TenSanPham & "%' Order By TenSanPham"
            'adapter = New OleDb.OleDbDataAdapter(query, dbConn)
            'adapter.Fill(dtSanPhamTheoKhachHang)
            'Dim newRow As DataRow
            'For Each dr As DataRow In dtSanPhamTheoKhachHang.Rows
            '    newRow = dtSanPham.NewRow
            '    newRow.Item("IDSanPham") = dr.Item("IDSanPham")
            '    newRow.Item("MaLoai") = dr.Item("MaLoai")
            '    newRow.Item("TenLoai") = dr.Item("TenLoai")
            '    newRow.Item("MaSanPham") = dr.Item("MaSanPham")
            '    newRow.Item("TenSanPham") = dr.Item("TenSanPham")
            '    newRow.Item("TenDonViTinh") = dr.Item("TenDonViTinh")
            '    newRow.Item("DonGia") = dr.Item("DonGia")
            '    newRow.Item("SoLuongTon") = dr.Item("SoLuongTon")
            '    newRow.Item("Type") = dr.Item("Type")
            '    dtSanPham.Rows.Add(newRow)
            'Next
            'Dim newNumItem As Integer = dtSanPham.Rows.Count - 1
            'dbConn.Close()
            'dtSanPham.DefaultView.Sort = "MaSanPham ASC"
            'dgvSanPham.DataSource = dtSanPham
            'Dim cellEdit As DataGridViewCell
            'cellEdit = dgvSanPhamHopdong_Tab1.CurrentRow.Cells(0)
            'dgvSanPhamHopdong_Tab1.CurrentCell = cellEdit
            'dgvSanPhamHopdong_Tab1.CurrentCell.Selected = True
        End Sub
        '-------------------Load Nhân Viên Tiếp Thị----------------
        Private Sub NhanVienTiepThi_Load()
            Try
                Dim dbConn As New OleDb.OleDbConnection
                Dim dataAccess As New DataAccess
                Dim dsNhanVienTiepThi As New DataSet
                Dim dtNhanVienTiepThi As New DataTable
                Dim query As String = "Select NhanVienTiepThiId,TenNhanVienTiepThi From NhanVienTiepThi Union Select pkey as NhanVienTiepThi,[name] as TenNhanVienTiepThi From KhongXacDinh Order By NhanVienTiepThiId ASC"
                Dim adapter As OleDb.OleDbDataAdapter
                dataAccess.ConnectDatabase_DBAccess(dbConn)
                adapter = New OleDb.OleDbDataAdapter(query, dbConn)
                adapter.Fill(dsNhanVienTiepThi)
                dbConn.Close()
                dtNhanVienTiepThi = dsNhanVienTiepThi.Tables(0)
                cbxNhanVienTT.DataSource = dtNhanVienTiepThi
                cbxNhanVienTT.ValueMember = "NhanVienTiepThiId"
                cbxNhanVienTT.DisplayMember = "TenNhanVienTiepThi"
            Catch ex As Exception
                ShowError()
            End Try
        End Sub
#End Region
#Region "Control Events"
        '-----------Format Sản Phẩm Khi Số Lượng Tồn=0-----------------------'
        Private Sub dgvSanPham_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs)
            Try
                'Dim newFont As New Font(dgvSanPham.Font, FontStyle.Bold)
                'For i As Integer = 0 To dgvSanPham.Rows.Count - 1
                '    Dim SoLuongTon As String = dgvSanPham.Item("SoLuongTon", i).Value
                '    If SoLuongTon = "0.00" Then
                '        SoLuongTon = "0"
                '    End If
                '    If Single.Parse(SoLuongTon) <= 0 Then
                '        dgvSanPham.Rows(i).DefaultCellStyle.ForeColor = Color.Red
                '        dgvSanPham.Rows(i).DefaultCellStyle.Font = newFont
                '    End If
                '    If dgvSanPham.Item("Type", i).Value = "1" Then
                '        dgvSanPham.Rows(i).DefaultCellStyle.BackColor = Color.YellowGreen
                '        dgvSanPham.Rows(i).DefaultCellStyle.Font = newFont
                '    End If

                'Next
            Catch ex As Exception

            End Try
        End Sub
#End Region
#Region "Các Hàm Liên Quan Tới Grid Nhập Hàng"
        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Xử lý sự kiện khi nhập số lượng và đơn giá vào row mà cell mã sản phẩm chưa có thì ko cho nhập
        ''' </summary>
        ''' <remarks>
        ''' 
        ''' </remarks>
        ''' <history>
        '''   [lamtn] 18/02/2011  Created
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Private Sub dgvSanPhamHopdong_Tab1_CellBeginEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellCancelEventArgs) Handles dgvSanPhamHopdong_Tab1.CellBeginEdit
            Try
                'If e.ColumnIndex = 5 Or e.ColumnIndex = 6 Then
                '    Dim MasanPham As Object = dgvSanPhamHopdong_Tab1(2, e.RowIndex).Value
                '    If TypeOf (MasanPham) Is String Then
                '        If String.IsNullOrEmpty(MasanPham) Then
                '            e.Cancel = True
                '        End If
                '    ElseIf TypeOf (MasanPham) Is DBNull Then
                '        e.Cancel = True
                '    Else
                '    End If
                'End If
            Catch ex As Exception

            End Try
        End Sub
        Private Sub dgvSanPhamHopdong_Tab1_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvSanPhamHopdong_Tab1.CellEndEdit

            'Try
            '    If KeyEnterOnGridDetail Then
            '        dgvSanPhamHopdong_Tab1.Focus()
            '        dgvSanPhamHopdong_Tab1.EndEdit()
            '    Else
            '        dgvSanPham.Focus()
            '    End If
            '    KeyEnterOnGridDetail = False
            'Catch ex As Exception

            'End Try
        End Sub
#End Region
#Region "Hàm tiện ích"
        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Tạo số hóa đơn
        ''' </summary>
        ''' <remarks>
        ''' 
        ''' </remarks>
        ''' <history>
        '''   [lamtn] 19/02/2011  Created
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Private Sub TaoSoHoaDon()
            Try
                Dim dbConn As New OleDb.OleDbConnection
                Dim dataAccess As New DataAccess
                Dim dtNumKey As New DataTable
                Dim query As String = "Select Max(Convert(Int,So)) From DonHangBan"
                Dim dbCommand As OleDb.OleDbCommand
                dataAccess.ConnectDatabase_DBAccess(dbConn)
                Dim SoHoaDon As Integer
                dbCommand = New OleDb.OleDbCommand(query, dbConn)
                If IsDBNull(dbCommand.ExecuteScalar()) Or dbCommand.ExecuteScalar().ToString = "" Then
                    txtSo.Text = "1"
                Else
                    SoHoaDon = Integer.Parse(dbCommand.ExecuteScalar()) + 1
                    txtSo.Text = SoHoaDon.ToString
                End If
                dbConn.Close()
            Catch ex As Exception
                MessageBox.Show(ex.ToString)
            End Try
        End Sub
        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Tạo số hóa đơn
        ''' </summary>
        ''' <remarks>
        ''' 
        ''' </remarks>
        ''' <history>
        '''   [lamtn] 19/02/2011  Created
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Private Sub TinhTienHangChuaThue()
            Try
                'Dim ThanhTienHangHoa As Integer = 0
                'fix VND,USD,SGD 
                Dim ThanhTienHangHoa As Double
                For i As Integer = 0 To dgvSanPhamHopdong_Tab1.Rows.Count - 1
                    Dim IDSanPham As Integer = Integer.Parse(dgvSanPhamHopdong_Tab1("IDSanPham", i).Value)
                    Dim LoaiPhi As String = dgvSanPhamHopdong_Tab1("LoaiPhi", i).Value
                    'Dim iThanhTien As Integer
                    Dim iThanhTien As Double
                    If IDSanPham > 0 And LoaiPhi = "HangHoa" Then
                        iThanhTien = dgvSanPhamHopdong_Tab1("ThanhTien", i).Value
                        ThanhTienHangHoa = ThanhTienHangHoa + iThanhTien
                    End If
                Next
                'fix VND,USD,SGD 
                'Dim ThanhTienGiamTru As Integer = 0
                Dim ThanhTienGiamTru As Double = 0
                For i As Integer = 0 To dgvSanPhamHopdong_Tab1.Rows.Count - 1
                    Dim IDSanPham As Integer = Integer.Parse(dgvSanPhamHopdong_Tab1("IDSanPham", i).Value)
                    Dim LoaiPhi As String = dgvSanPhamHopdong_Tab1("LoaiPhi", i).Value
                    'fix VND,USD,SGD 
                    'Dim iThanhTien As Integer
                    Dim iThanhTien As Double
                    If IDSanPham > 0 And LoaiPhi = "GiamTru" Then
                        iThanhTien = dgvSanPhamHopdong_Tab1("ThanhTien", i).Value
                        ThanhTienGiamTru = ThanhTienGiamTru + iThanhTien
                    End If
                Next
                'Dim CongTienHang As Integer = ThanhTienHangHoa - ThanhTienGiamTru
                'fix VND,USD,SGD 
                Dim CongTienHang As Double = ThanhTienHangHoa - ThanhTienGiamTru
                txtCongTienHang.Text = CongTienHang.ToString("N02", US)
            Catch ex As Exception
                Throw
            End Try
        End Sub
        Private Sub TinhTienThueVAT()
            Try
                Dim TienThueVAT As Double
                Dim CongTienHang As Double
                Dim VAT As Double = txtVat.Value
                If txtCongTienHang.Text = "" Then
                    CongTienHang = 0
                Else
                    CongTienHang = Double.Parse(txtCongTienHang.Text)
                End If
                If comboTien.SelectedValue = "VND" Then
                    TienThueVAT = LamTron((CongTienHang * VAT) / 100, 0)
                ElseIf comboTien.SelectedValue = "USD" Or comboTien.SelectedValue = "SGD" Then
                    TienThueVAT = LamTron((CongTienHang * VAT) / 100, 2)
                End If
                txtTienThueVAT.Text = TienThueVAT.ToString("N02", US)
            Catch ex As Exception

            End Try
        End Sub
        Private Sub TinhTienThueDaThue()
            Try
                Dim TienThueVAT As Double
                Dim CongTienHang As Double
                Dim TongThanhToan As Double
                If txtCongTienHang.Text = "" Then
                    CongTienHang = 0
                Else
                    CongTienHang = Double.Parse(txtCongTienHang.Text)
                End If
                If txtTienThueVAT.Text = "" Then
                    TienThueVAT = 0
                Else
                    TienThueVAT = Double.Parse(txtTienThueVAT.Text)
                End If
                TongThanhToan = TienThueVAT + CongTienHang
                If comboTien.SelectedValue = "VND" Then
                    TongThanhToan = LamTron(TongThanhToan)
                ElseIf comboTien.SelectedValue = "USD" Or comboTien.SelectedValue = "SGD" Then
                    TongThanhToan = LamTron(TongThanhToan, 2)
                End If
                txtTongThanhToan.Text = TongThanhToan.ToString("N02", US)
            Catch ex As Exception

            End Try
        End Sub
        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Format Cell To Defaul Value
        ''' </summary>
        ''' <remarks>
        ''' 
        ''' </remarks>
        ''' <history>
        '''   [lamtn] 19/02/2011  Created
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Private Sub FormatNumberCell(ByVal Cell As DataGridViewCell)
            Try
                Dim CellValue As Object = Cell.Value
                If TypeOf (CellValue) Is String Then
                    If String.IsNullOrEmpty(CellValue) Then
                        Cell.Value = "0"
                    End If
                ElseIf (IsDBNull(CellValue)) Or (CellValue Is Nothing) Then
                    Cell.Value = "0"
                End If
            Catch ex As Exception

            End Try
        End Sub
#End Region
#End Region
#Region "Tab 2"

#End Region

#Region "Load Data"

        '-----------Load Bảng Mục Giảm Trừ Hóa Đơn-----------------------'
        Private Sub GiamTruHoaDon()
            Try
                Dim dbConn As New OleDb.OleDbConnection
                Dim dataAccess As New DataAccess
                Dim dtMucTruHoaDon As New DataTable
                Dim query As String = "select MucTruHoaDonId,TenMucTru,Tru As TruPhanTram,0 As [Type] from muctruhoadon"
                Dim adapter As OleDb.OleDbDataAdapter
                dataAccess.ConnectDatabase_DBAccess(dbConn)
                adapter = New OleDb.OleDbDataAdapter(query, dbConn)
                adapter.Fill(dtMucTruHoaDon)
                'dtMucTruHoaDon.Columns.Add("TruPhanTram")
                'For i As Integer = 0 To dtMucTruHoaDon.Rows.Count - 1
                '    Dim s As String = dtMucTruHoaDon.Rows(i)("TheoPhanTram")
                '    If dtMucTruHoaDon.Rows(i)("TheoPhanTram") = "Yes" Then
                '        dtMucTruHoaDon.Rows(i)("TruPhanTram") = dtMucTruHoaDon.Rows(i)("Tru")
                '    Else
                '        dtMucTruHoaDon.Rows(i)("TruPhanTram") = dtMucTruHoaDon.Rows(i)("Tru")
                '    End If
                'Next
                dgvGiamTru.AutoGenerateColumns = False
                dgvGiamTru.DataSource = dtMucTruHoaDon
                dbConn.Close()
            Catch ex As Exception
                MessageBox.Show(ex.ToString)
            End Try
        End Sub

        Private Sub GiamTruHoaDonTheoKhachHang(ByVal KhachHangId As String)
            Try
                Dim dbConn As New OleDb.OleDbConnection
                Dim dataAccess As New DataAccess
                Dim dtMucTruHoaDon As New DataTable
                Dim query As String = "select MucTruHoaDonID,TenMucTru,Tru As TruPhanTram,TheoPhanTram,0 As [Type] from muctruhoadon" & _
                " union select MucTruHoaDonTheoKhachHangId,TenMucTru,Tru,TheoPhanTram,1 As [Type] from muctruhoadontheokhachhang" & _
                " Where KhachHangId=" & KhachHangId
                Dim adapter As OleDb.OleDbDataAdapter
                dataAccess.ConnectDatabase_DBAccess(dbConn)
                adapter = New OleDb.OleDbDataAdapter(query, dbConn)
                adapter.Fill(dtMucTruHoaDon)
                'dtMucTruHoaDon.Columns.Add("TruPhanTram")
                'For i As Integer = 0 To dtMucTruHoaDon.Rows.Count - 1
                '    Dim s As String = dtMucTruHoaDon.Rows(i)("TheoPhanTram")
                '    If dtMucTruHoaDon.Rows(i)("TheoPhanTram") = "Yes" Then
                '        dtMucTruHoaDon.Rows(i)("TruPhanTram") = dtMucTruHoaDon.Rows(i)("Tru")
                '    Else
                '        dtMucTruHoaDon.Rows(i)("TruPhanTram") = dtMucTruHoaDon.Rows(i)("Tru")
                '    End If
                'Next
                dgvGiamTru.AutoGenerateColumns = False
                dgvGiamTru.DataSource = dtMucTruHoaDon
                dbConn.Close()

            Catch ex As Exception
                MessageBox.Show(ex.ToString)
            End Try
        End Sub
        'Format

        '-----------Load Bảng Loại Sản Phẩm-----------------------'
        Public Sub LoaiSanPham_Load()
            Try
                'Dim dbConn As New OleDb.OleDbConnection
                'Dim dataAccess As New DataAccess
                'Dim dsLoaiSanPham As New DataSet
                'Dim dtLoaiSanPham As New DataTable
                'Dim query As String = "Select IdLoai,MaLoai From LoaiSanPham"
                'Dim adapter As OleDb.OleDbDataAdapter
                'dataAccess.ConnectDatabase_DBAccess(dbConn)
                'adapter = New OleDb.OleDbDataAdapter(query, dbConn)
                'adapter.Fill(dsLoaiSanPham)
                'dbConn.Close()
                'dtLoaiSanPham = dsLoaiSanPham.Tables(0)
                'cbxLoaisanpham.DataSource = dtLoaiSanPham
                'cbxLoaisanpham.DisplayMember = "MaLoai"
                'cbxLoaisanpham.ValueMember = "IdLoai"
            Catch ex As Exception
                MessageBox.Show(ex.ToString)
            End Try

        End Sub




#End Region
#Region "Thêm Sản Phầm Bằng Tay"

#End Region
#Region "Tìm kiếm Sản Phẩm"

        Private Class GiaInfo
            Dim _Gia As Single
            Public Sub New(ByVal Gia As Single)
                _Gia = Gia
            End Sub
            Public Function Gia() As Single
                Return _Gia
            End Function
            Public Overrides Function ToString() As String
                Return Format(_Gia, "N2")
            End Function
        End Class
#End Region
#Region "Thêm Sản Phẩm"
        '----------Tạo Table Sản Phẩm-------------
        Protected Function InitOrderTable() As DataTable
            Dim dtTable As DataTable = New DataTable()
            Try
                'RowIndex 
                Dim RowIndex As DataColumn = New DataColumn("RowIndex")
                RowIndex.DataType = System.Type.GetType("System.Int32")
                dtTable.Columns.Add(RowIndex)

                Dim IDSanPham As DataColumn = New DataColumn("IDSanPham")
                IDSanPham.DataType = System.Type.GetType("System.Int32")
                dtTable.Columns.Add(IDSanPham)

                Dim MaSanPham As DataColumn = New DataColumn("MaSanPham")
                MaSanPham.DataType = System.Type.GetType("System.String")
                dtTable.Columns.Add(MaSanPham)

                Dim TenSanPham As DataColumn = New DataColumn("TenSanPham")
                TenSanPham.DataType = System.Type.GetType("System.String")
                dtTable.Columns.Add(TenSanPham)

                Dim TenQuyCach As DataColumn = New DataColumn("TenQuyCach")
                TenQuyCach.DataType = System.Type.GetType("System.String")
                dtTable.Columns.Add(TenQuyCach)

                Dim SoLuong As DataColumn = New DataColumn("SoLuong")
                SoLuong.DataType = System.Type.GetType("System.String")
                dtTable.Columns.Add(SoLuong)

                Dim DonGia As DataColumn = New DataColumn("DonGia")
                DonGia.DataType = System.Type.GetType("System.String")
                dtTable.Columns.Add(DonGia)

                Dim IsManyPrice As DataColumn = New DataColumn("IsManyPrice")
                IsManyPrice.DataType = System.Type.GetType("System.String")
                dtTable.Columns.Add(IsManyPrice)

                Dim ThanhTien As DataColumn = New DataColumn("ThanhTien")
                ThanhTien.DataType = System.Type.GetType("System.String")
                dtTable.Columns.Add(ThanhTien)

                Dim LoaiPhi As DataColumn = New DataColumn("LoaiPhi")
                LoaiPhi.DataType = System.Type.GetType("System.String")
                dtTable.Columns.Add(LoaiPhi)

                Return dtTable
            Catch ex As Exception
                Throw
            End Try
        End Function
        Private Sub txtVat_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
            If Not Char.IsDigit(e.KeyChar) And Not Char.IsControl(e.KeyChar) Then
                e.Handled = True
            End If
        End Sub
        'Private Sub txtSoLuong_Leave(ByVal sender As Object, ByVal e As System.EventArgs)
        '    Try
        '        While txtSoLuong.Text.StartsWith(".")
        '            txtSoLuong.Text = txtSoLuong.Text.Remove(0, 1)
        '        End While
        '        While txtSoLuong.Text.EndsWith(".")
        '            txtSoLuong.Text = txtSoLuong.Text.Remove(txtSoLuong.Text.ToString.ToString.Length - 1, 1)
        '        End While
        '        txtSoLuong.Text = FormatOnlyDotted(txtSoLuong.Text.ToString)
        '    Catch ex As Exception

        '    End Try
        'End Sub
        'Nếu nhiều dấu chấm thì chỉ lẩy 1 dấu chấm thui
        Private Function FormatOnlyDotted(ByVal TextInput As String) As String
            Try
                If TextInput.Split(".").Length > 2 Then
                    'format
                    While TextInput.Split(".").Length > 2
                        Dim iRemove As Integer
                        iRemove = TextInput.IndexOf(".")
                        TextInput = TextInput.Remove(iRemove, 1)
                    End While
                End If
                Return TextInput
            Catch ex As Exception
                Throw
            End Try
        End Function
        'Hàm Tính Tổng Tiền Hàng Hóa Trong Hóa Đơn
        Private Function TinhTongTienHangHoa(ByVal dtSanPham As DataTable) As Double
            Try
                Dim sRet As Double = 0
                Dim rowHangHoa() As DataRow
                rowHangHoa = dtSanPham.Select("LoaiPhi='HangHoa'")
                For i As Integer = 0 To rowHangHoa.Length - 1
                    sRet = sRet + rowHangHoa(i).Item("ThanhTien")
                Next
                Return sRet
            Catch ex As Exception
                ShowError()
            End Try
        End Function
        'Hàm Tính Tổng Tiền Giảm Trừ Trong Hóa Đơn
        Private Function TinhTongTienGiamTru(ByVal dtSanPham As DataTable) As Double
            Try
                Dim sRet As Double = 0
                Dim rowGiamTru() As DataRow
                rowGiamTru = dtSanPham.Select("LoaiPhi='GiamTru'")
                For i As Integer = 0 To rowGiamTru.Length - 1
                    'sRet = sRet + Single.Parse(rowGiamTru(i).Item("ThanhTien").ToString, Globalization.NumberStyles.Currency)
                    sRet = sRet + rowGiamTru(i).Item("ThanhTien")
                Next
                Return sRet
            Catch ex As Exception
                ShowError()
            End Try
        End Function
        'Hàm Tính Lại Các Khoản Giảm Trừ Theo % Khi Cập Nhật Sản Phẩm Hóa Đơn
        Private Sub CapNhatKhoanGiamTruHoaDon(ByRef dtSanPham As DataTable)
            Try
                Dim TongTienHangHoa As Single = 0
                Dim ThanhTien As Single
                Dim rowGiamTruTheoPhanTram() As DataRow
                Dim sDonGia As String
                TongTienHangHoa = TinhTongTienHangHoa(dtSanPham)
                rowGiamTruTheoPhanTram = dtSanPham.Select("LoaiPhi='GiamTru'")
                For i As Integer = 0 To rowGiamTruTheoPhanTram.Length - 1
                    sDonGia = rowGiamTruTheoPhanTram(i).Item("DonGia").ToString
                    If sDonGia.IndexOf("%") > 0 Then
                        sDonGia = sDonGia.Substring(0, sDonGia.IndexOf("%")).Trim()
                        ThanhTien = 0
                        ThanhTien = (TongTienHangHoa * Single.Parse(sDonGia)) / 100
                        rowGiamTruTheoPhanTram(i).Item("ThanhTien") = Format(ThanhTien, "N2")
                        dtSanPham.AcceptChanges()
                    End If
                Next
            Catch ex As Exception
                ShowError()
            End Try
        End Sub
        'Hàm Tính Thông Tin Hóa Đơn
        Private Sub ThongTinTienHoaDon()
            Try
                ''----------Tính Tổng Tiền Hàng --------------
                'Dim TongTienHangHoa As Single = 0
                'Dim TongTienGiamTru As Single = 0
                'Dim TongTienHang As Single = 0
                'TongTienHangHoa = TinhTongTienHangHoa(dtSanPhamHD)
                'TongTienGiamTru = TinhTongTienGiamTru(dtSanPhamHD)
                'TongTienHang = TongTienHangHoa - TongTienGiamTru
                'txtCongTienHang.Text = Format(TongTienHang, "N2")
                ''----------Tính Tiến Thuế VAT --------------
                'Dim ThueVAT As Single = 0
                'ThueVAT = (Single.Parse(txtVAT.Text) * TongTienHang) / 100
                'txtTienThueVAT.Text = Format(ThueVAT, "N2")
                ''----------Tính Tổng Tiền Thanh Toán--------
                'Dim TongTienThanhToan As Single = 0
                ''Dim sTongTienThanhToan As String
                'TongTienThanhToan = TongTienHang + ThueVAT
                ''sTongTienThanhToan = CDec(TongTienThanhToan.ToString).ToString("N", Globalization.CultureInfo.CreateSpecificCulture("vi-vn")).ToString()
                'txtTongThanhToan.Text = Format(TongTienThanhToan, "N2")
                'txtTienVietBangChu.Text = Num2Text(TongTienThanhToan, False)
            Catch ex As Exception

            End Try
        End Sub
#End Region
#Region "Thêm Khách Hàng"
        Sub KhachHang_Quick_Search()
            Try
                Dim dbConn As New OleDb.OleDbConnection
                Dim dataAccess As New DataAccess
                Dim dsKhachHang As New DataSet
                Dim dtKhachHang As New DataTable
                Dim query As String = "Select KhachHangId,MaKhachHang,TenKhachHang,SoDienThoai,DiaChi From DanhMucKhachHang Where Xoa=0 And TenKhachHang Like N'%" & txtTenKhachHang.Text.Trim & "%'"
                Dim adapter As OleDb.OleDbDataAdapter
                dataAccess.ConnectDatabase_DBAccess(dbConn)
                adapter = New OleDb.OleDbDataAdapter(query, dbConn)
                adapter.Fill(dsKhachHang)
                dbConn.Close()
                dtKhachHang = dsKhachHang.Tables(0)
                Panel_KhachHang.Visible = True
                dgv_KhachHang_QuickSearch.AutoGenerateColumns = False
                dgv_KhachHang_QuickSearch.DataSource = dtKhachHang
            Catch ex As Exception
                MessageBox.Show(ex.ToString())
            End Try
        End Sub

        Private Sub txtTenKhachHang_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtTenKhachHang.KeyDown
            Try
                If e.KeyCode = Keys.Enter Then
                    lblKhachHangId.Text = dgv_KhachHang_QuickSearch.Rows(dgv_KhachHang_QuickSearch.CurrentCell.RowIndex).Cells("KhachHangId_Search").Value.ToString()
                    '---------Lấy Thống Tin Khách Hàng----------
                    Dim dbConn As New OleDb.OleDbConnection
                    Dim dataAccess As New DataAccess
                    Dim dsTinhThanh As New DataSet
                    Dim dtTinhThanh As New DataTable
                    Dim query As String = "Select * From DanhMucKhachHang Where KhachHangId=" & lblKhachHangId.Text
                    Dim adapter As OleDb.OleDbDataAdapter
                    dataAccess.ConnectDatabase_DBAccess(dbConn)
                    adapter = New OleDb.OleDbDataAdapter(query, dbConn)
                    adapter.Fill(dsTinhThanh)

                    dtTinhThanh = dsTinhThanh.Tables(0)
                    '
                    txtMaKhachHang.Text = IIf(IsDBNull(dtTinhThanh.Rows(0)("CodeKhachHang")), "", dtTinhThanh.Rows(0)("CodeKhachHang"))
                    txtTenKhachHang.Text = IIf(IsDBNull(dtTinhThanh.Rows(0)("TenKhachHang")), "", dtTinhThanh.Rows(0)("TenKhachHang"))
                    txtDiaChi.Text = dtTinhThanh.Rows(0)("DiaChi")
                    txtMaSoThue.Text = IIf(IsDBNull(dtTinhThanh.Rows(0)("MaSoThue")), "", dtTinhThanh.Rows(0)("MaSoThue"))
                    cbxNhanVienTT.SelectedValue = Integer.Parse(IIf(IsDBNull(dtTinhThanh.Rows(0)("NhanVienTiepThiId")), 0, dtTinhThanh.Rows(0)("NhanVienTiepThiId").ToString))
                    Panel_KhachHang.Visible = False
                    dbConn.Close()
                    txtHinhThucThanhToan.Focus()
                ElseIf e.KeyCode = Keys.Up Or e.KeyCode = Keys.Down Then

                End If
            Catch ex As Exception

            End Try
        End Sub
        Private Sub txtTenKhachHang_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtTenKhachHang.KeyUp
            Try
                If txtTenKhachHang.Text <> "" Then
                    KhachHang_Quick_Search()
                    If e.KeyCode = Keys.Up Or e.KeyCode = Keys.Down Then
                        dgv_KhachHang_QuickSearch.Focus()
                        Panel_KhachHang.Visible = True
                    End If
                Else
                    Panel_KhachHang.Visible = False
                    lblKhachHangId.Text = "0"
                    txtDiaChi.Text = ""
                    txtMaSoThue.Text = ""
                    txtMaKhachHang.Text = ""
                End If
            Catch ex As Exception
                MessageBox.Show(ex.ToString())
            End Try
        End Sub

        Private Sub txtDaiLy_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtDaiLy.KeyDown
            Try
                If e.KeyCode = Keys.Enter Then
                    txtDaiLy.Text = dgvDaiLy("TenDaiLy", dgvDaiLy.CurrentCell.RowIndex).Value
                    lblDaiLyId.Text = dgvDaiLy("DaiLyId", dgvDaiLy.CurrentCell.RowIndex).Value
                    Panel_DaiLy.Visible = False
                    dgvSanPhamHopdong_Tab1.Focus()
                End If
            Catch ex As Exception

            End Try
        End Sub

        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Xử lý sự kiện khi đánh các phím chữ vào txtDaiLy Thi Show Danh Sách Đại Lý
        ''' </summary>
        ''' <remarks>
        ''' 
        ''' </remarks>
        ''' <history>
        '''   [lamtn] 18/02/2011  Created
        ''' </history>
        ''' -----------------------------------------------------------------------------
        ''' 
        Private Sub txtDaiLy_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtDaiLy.KeyUp
            Try
                If txtDaiLy.Text <> "" Then
                    DaiLy_Search()
                    If e.KeyCode = Keys.Up Or e.KeyCode = Keys.Down Then
                        dgvDaiLy.Focus()
                    End If
                Else
                    Panel_DaiLy.Visible = False
                End If
            Catch ex As Exception
                MessageBox.Show(ex.ToString())
            End Try
        End Sub
        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Xử lý sự kiện Show Danh Sách Đại Lý
        ''' </summary>
        ''' <remarks>
        ''' 
        ''' </remarks>
        ''' <history>
        '''   [lamtn] 18/02/2011  Created
        ''' </history>
        ''' -----------------------------------------------------------------------------
        ''' 
        Private Sub DaiLy_Search()
            Try
                Dim dbConn As New OleDb.OleDbConnection
                Dim dataAccess As New DataAccess
                Dim dsKhachHang As New DataSet
                Dim dtKhachHang As New DataTable
                Dim query As String = "Select KhachHangId,MaKhachHang,TenKhachHang,SoDienThoai,DiaChi From DanhMucKhachHang Where TenKhachHang Like N'%" & txtDaiLy.Text.Trim & "%'"
                Dim adapter As OleDb.OleDbDataAdapter
                dataAccess.ConnectDatabase_DBAccess(dbConn)
                adapter = New OleDb.OleDbDataAdapter(query, dbConn)
                adapter.Fill(dsKhachHang)
                dbConn.Close()
                dtKhachHang = dsKhachHang.Tables(0)
                Panel_DaiLy.Visible = True
                dgvDaiLy.AutoGenerateColumns = False
                dgvDaiLy.DataSource = dtKhachHang
            Catch ex As Exception
                MessageBox.Show(ex.ToString())
            End Try
        End Sub
        Private Sub dgvDaiLy_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles dgvDaiLy.KeyDown
            Try
                Select Case e.KeyCode
                    Case Keys.Down
                        Panel_DaiLy.Visible = True
                    Case Keys.Up
                        Panel_DaiLy.Visible = True
                    Case Keys.Enter
                        txtDaiLy.Text = dgvDaiLy("TenDaiLy", dgvDaiLy.CurrentCell.RowIndex).Value
                        lblDaiLyId.Text = dgvDaiLy("DaiLyId", dgvDaiLy.CurrentCell.RowIndex).Value
                        Panel_DaiLy.Visible = False
                        dgvSanPhamHopdong_Tab1.Focus()
                    Case Else
                        txtDaiLy.Focus()
                End Select
            Catch ex As Exception

            End Try
        End Sub

        Function IsNotExist(ByVal TenKhachHang As String) As Boolean
            Try
                Dim dbConn As New OleDb.OleDbConnection
                Dim dataAccess As New DataAccess
                Dim dsKhachHang As New DataSet
                Dim dtKhachHang As New DataTable
                Dim query As String = "Select Count(*) From DanhMucKhachHang Where LOWER(TenKhachHang)=N'" & TenKhachHang & "'"
                Dim dbCommand As OleDb.OleDbCommand
                dataAccess.ConnectDatabase_DBAccess(dbConn)
                dbCommand = New OleDb.OleDbCommand(query, dbConn)
                Dim iResult As Integer
                iResult = dbCommand.ExecuteScalar()
                If iResult = 0 Then
                    Return True
                Else
                    Return False
                End If
                dbConn.Close()
            Catch ex As Exception
                MessageBox.Show(ex.ToString())
            End Try
        End Function
#End Region
#Region "Thêm mục trừ hóa đơn"

        Private Sub dgvGiamTru_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs)
            Try
                If e.ColumnIndex = 1 And e.RowIndex > -1 Then
                    If dgvGiamTru(e.ColumnIndex, e.RowIndex).Value = 1 Then
                        'khoản giảm trừ
                        Dim newRow As DataRow
                        Dim sMucTru As String
                        Dim MucTru As Single
                        newRow = dtSanPhamHD.NewRow
                        newRow.Item("IDSanPham") = dgvGiamTru.Item("MucTruHoaDonId", e.RowIndex).Value
                        newRow.Item("MaSanPham") = dgvGiamTru.Item("TenMucTru", e.RowIndex).Value
                        newRow.Item("TenSanPham") = dgvGiamTru.Item("TenMucTru", e.RowIndex).Value
                        newRow.Item("SoLuong") = ""
                        sMucTru = dgvGiamTru.Item("Tru", e.RowIndex).Value
                        newRow.Item("DonGia") = sMucTru
                        'kiểm tra nếu mục giảm trừ này đã được thêm rồi thì không thêm nữa
                        Dim rowExist() As DataRow
                        rowExist = dtSanPhamHD.Select("IDSanPham=" & dgvGiamTru.Item("MucTruHoaDonId", e.RowIndex).Value & " And LoaiPhi='GiamTru'")
                        If rowExist.Length > 0 Then
                            Exit Sub
                        End If
                        If sMucTru.IndexOf("%") > 0 Then
                            sMucTru = sMucTru.Substring(0, sMucTru.IndexOf("%")).Trim()
                            'Tính Tổng Tiền Hàng Trong Hóa Đơn Hiện Có 
                            Dim TongTien As Single
                            Dim rowHangHoa() As DataRow
                            rowHangHoa = dtSanPhamHD.Select("LoaiPhi='HangHoa'")
                            For i As Integer = 0 To rowHangHoa.Length - 1
                                TongTien = TongTien + Single.Parse(rowHangHoa(i).Item("ThanhTien"))
                            Next
                            MucTru = (TongTien * Single.Parse(sMucTru)) / 100
                        Else
                            MucTru = Single.Parse(sMucTru)
                        End If
                        newRow.Item("ThanhTien") = Format(MucTru, "N2")
                        newRow.Item("LoaiPhi") = "GiamTru"
                        dtSanPhamHD.Rows.Add(newRow)
                    Else
                        Dim IDSanPham As String
                        IDSanPham = dgvGiamTru.Item("MucTruHoaDonId", e.RowIndex).Value
                        Dim rowDelete() As DataRow
                        rowDelete = dtSanPhamHD.Select("IDSanPham=" & IDSanPham & " And LoaiPhi='GiamTru'")
                        rowDelete(0).Delete()
                        dtSanPhamHD.AcceptChanges()
                    End If
                    dgvSanPhamHopdong_Tab1.AutoGenerateColumns = False
                    dgvSanPhamHopdong_Tab1.DataSource = dtSanPhamHD
                    ThongTinTienHoaDon()
                End If
            Catch ex As Exception

            End Try
        End Sub
#End Region
#Region "Lưu Thông Tin Đơn Hàng"
        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Lưu thông tin đơn hàng và chi tiết đơn hàng bán
        ''' </summary>
        ''' <remarks>
        ''' 
        ''' </remarks>
        ''' <history>
        '''   [lamtn] 18/02/2011  Created
        '''   [lamtn] 19/02/2011 fix -   
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Private Sub cmdLuu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdLuu.Click
            Try
                Order_Save()
                If cbxTruKho.Checked Then
                    Order_TruKho()
                End If
                Order_Clear()
            Catch ex As Exception
                MessageBox.Show(ex.ToString())
            End Try
        End Sub
#End Region
#Region "Chỉnh sửa đơn hàng"
        Private Sub ChinhSuaKhoanGiamTru(ByVal dtSanPham As DataTable)
            Try
                Dim cellChecbox As DataGridViewCheckBoxCell
                'For j As Integer = 0 To dgvGiamTru.Rows.Count - 1
                '    cellChecbox = dgvGiamTru.Item("Chon", j)
                '    cellChecbox.TrueValue = 1
                '    cellChecbox.FalseValue = 0
                'Next
                Dim rowGiamTruTheoPhanTram() As DataRow
                rowGiamTruTheoPhanTram = dtSanPham.Select("LoaiPhi='GiamTru'")
                For i As Integer = 0 To rowGiamTruTheoPhanTram.Length - 1
                    For j As Integer = 0 To dgvGiamTru.Rows.Count - 1
                        If dgvGiamTru.Item("MucTruHoaDonId", j).Value = rowGiamTruTheoPhanTram(i).Item("IDSanPham") Then
                            cellChecbox = dgvGiamTru.Item("Chon", j)
                            cellChecbox.Value = 1
                        End If
                    Next
                Next
            Catch ex As Exception

            End Try
        End Sub
        Private Sub MenuChinhSuaHoaDon_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
            Try
                Dim IdDonHangBan As Integer = Integer.Parse(dgvKhachHang.Rows(RowEditIndex).Cells("IdDonHangBan").Value.ToString)
                'check TrangThai
                'check tình trạng, nếu đơn hàng đã duyệt thì không thể xóa
                Dim dbConn As New OleDb.OleDbConnection
                Dim dataAccess As New DataAccess
                Dim query As String
                dataAccess.ConnectDatabase_DBAccess(dbConn)
                Dim TrangThai As String = ""
                Dim dbCommand As OleDb.OleDbCommand
                query = "Select TrangThai From DonHangBan Where IdDonHangBan=" & IdDonHangBan
                dbCommand = New OleDbCommand(query, dbConn)
                TrangThai = dbCommand.ExecuteScalar()
                If TrangThai = "Đã duyệt" Then
                    MessageBox.Show("Đơn hàng đã được duyệt.Bạn không thể chỉnh sửa đơn hàng này", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error)
                    dbConn.Close()
                    Exit Sub
                End If
                '
                TabControl1.SelectedTab = cmdXemThongTinChiTiet
                'show info for edit
                Dim NgayBan As String = dtpTheoNgay.Value.ToString.Split(" ")(0)
                query = "Select * From DonHangBan Where IDDonHangBan=" & IdDonHangBan
                Dim dsThongKe As New DataSet
                Dim adapter As OleDb.OleDbDataAdapter
                adapter = New OleDb.OleDbDataAdapter(query, dbConn)
                adapter.Fill(dsThongKe)

                'Thong Tin Khach Hang
                txtTenKhachHang.Text = dsThongKe.Tables(0).Rows(0)("TenKhachHang")
                lblKhachHangId.Text = dsThongKe.Tables(0).Rows(0)("KhachHangId")
                txtDiaChi.Text = dsThongKe.Tables(0).Rows(0)("DiaChi")
                txtMaSoThue.Text = dsThongKe.Tables(0).Rows(0)("MaSoThue")
                dtpNgayHopDong.Value = dsThongKe.Tables(0).Rows(0)("NgayBan")
                txtMaKhachHang.Text = dsThongKe.Tables(0).Rows(0)("CodeKhachHang")
                txtHinhThucThanhToan.Text = dsThongKe.Tables(0).Rows(0)("HinhThucThanhToan")
                cbxNhanVienTT.SelectedValue = dsThongKe.Tables(0).Rows(0)("NhanVienTiepThiId")
                txtVat.Text = dsThongKe.Tables(0).Rows(0)("ThueVat")
                'Thong Tin Don Hang
                'khoi tao lai
                dtSanPhamHD = InitOrderTable()
                Dim newRow As DataRow
                Dim dsDonHang As New DataSet
                Dim dtDonHang As New DataTable
                query = "Select * From ChiTietDonHangBan Where IdDonHangBan=" & IdDonHangBan
                adapter = New OleDb.OleDbDataAdapter(query, dbConn)
                adapter.Fill(dsDonHang)
                dtDonHang = dsDonHang.Tables(0)
                For i As Integer = 0 To dtDonHang.Rows.Count - 1
                    newRow = dtSanPhamHD.NewRow
                    newRow.Item("IDSanPham") = dtDonHang.Rows(i)("IdSanPham")
                    newRow.Item("MaSanPham") = dtDonHang.Rows(i)("TenSanPham")
                    newRow.Item("TenSanPham") = dtDonHang.Rows(i)("TenSanPham")
                    newRow.Item("TenQuyCach") = dtDonHang.Rows(i)("TenQuyCach")
                    newRow.Item("SoLuong") = dtDonHang.Rows(i)("SoLuong")
                    newRow.Item("DonGia") = dtDonHang.Rows(i)("DonGia")
                    newRow.Item("ThanhTien") = dtDonHang.Rows(i)("ThanhTien")
                    newRow.Item("LoaiPhi") = dtDonHang.Rows(i)("LoaiPhi")
                    dtSanPhamHD.Rows.Add(newRow)
                Next

                dgvSanPhamHopdong_Tab1.AutoGenerateColumns = False
                dgvSanPhamHopdong_Tab1.DataSource = dtSanPhamHD
                dbConn.Close()
                ThongTinTienHoaDon()
                ChinhSuaKhoanGiamTru(dtSanPhamHD)
                IdDonHangBan_Edit = IdDonHangBan
            Catch ex As Exception
                MessageBox.Show(ex.ToString)
            End Try
            'End Thong Tin Don Hang        
        End Sub
#End Region
#Region "Xóa đơn hàng"

#End Region
#Region "Thống kê - báo cáo"
        '--------Tính tiền doanh thu của khách hàng trên 1 đơn hàng-------------------
        Private Function TinhDoanhThuKhachHangTheoDonHang(ByVal IdDonHangBan As Integer) As Single
            Try
                Dim sRet As Single = 0
                Try
                    Dim dbConn As New OleDb.OleDbConnection
                    Dim dataAccess As New DataAccess
                    Dim dtThanhTien As New DataTable
                    Dim query_Tien_HoaDon As String
                    Dim adapter As OleDb.OleDbDataAdapter
                    Dim TongTienHoaDon As Integer = 0
                    query_Tien_HoaDon = String.Format("Select ThanhTien From ChiTietDonHangBan Where Xoa=0 And LoaiPhi='HangHoa' And IdDonHangBan={0} ", IdDonHangBan)
                    dataAccess.ConnectDatabase_DBAccess(dbConn)
                    adapter = New OleDb.OleDbDataAdapter(query_Tien_HoaDon, dbConn)
                    adapter.Fill(dtThanhTien)
                    For i As Integer = 0 To dtThanhTien.Rows.Count - 1
                        sRet = sRet + Single.Parse(dtThanhTien.Rows(i)("ThanhTien"))
                    Next
                    Return sRet
                Catch ex As Exception
                    MessageBox.Show("Có lỗi trong quá trình xử lý.Vui lòng thử lại")
                End Try
            Catch ex As Exception

            End Try
        End Function
#End Region
#Region "Thống kê theo ngày"
        Sub Report_TheoNgay()
            Dim TrangThai As String = ""
            Dim TuNgay As Integer = ConvertDateToInt(dtpTheoNgay.Value.ToString.Split(" ")(0))
            Dim DenNgay As Integer = ConvertDateToInt(dtpTheoNgay.Value.ToString.Split(" ")(0))
            If RadioButton3.Checked Then
                TrangThai = "Tất cả"
            ElseIf RadioButton1.Checked Then
                TrangThai = "Chưa duyệt"
            ElseIf RadioButton2.Checked Then
                TrangThai = "Đã duyệt"
            ElseIf RadioButton4.Checked Then
                TrangThai = "Đã hủy"
            End If
            Dim TongTien As Single = 0
            Dim dtThongKe As List(Of DonHang)
            Dim controller As New DonHangBLL
            dtThongKe = controller.DonHangBan_GetItems(TrangThai, TuNgay, DenNgay)
            Dim sThanhTien As String
            For i As Integer = 0 To dtThongKe.Count - 1
                formatDate2VN(dtThongKe(i).NgayBan)
                TongTien = TongTien + dtThongKe(i).TongTien
                sThanhTien = CDec(dtThongKe(i).TongTien.ToString).ToString("N", Globalization.CultureInfo.CreateSpecificCulture("vi-vn")).ToString()
                dtThongKe(i).DoanhThu = sThanhTien
            Next
            lblSum.Text = CDec(TongTien.ToString).ToString("N", Globalization.CultureInfo.CreateSpecificCulture("vi-vn")).ToString()
            dgvKhachHang.AutoGenerateColumns = False
            dgvKhachHang.DataSource = dtThongKe
            If dgvKhachHang.Rows.Count - 1 > 0 Then
                dgvKhachHang.Rows(0).Selected = True
            End If
        End Sub
#End Region
#Region "Report Theo Tháng"
        Private Sub Report_TheoThang()
            Dim TrangThai As String = ""
            Dim Thang As MonthInfo
            Thang = CType(cbxTheoThang.SelectedItem, MonthInfo)
            If Thang Is Nothing Then
                MessageBox.Show("Bạn chưa chọn tháng.Vui lòng kiểm tra lại!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Sub
            End If
            Dim Nam As YearInfo
            Nam = CType(cbxNamTheoThang.SelectedItem, YearInfo)
            If Nam Is Nothing Then
                MessageBox.Show("Bạn chưa chọn năm.Vui lòng kiểm tra lại!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Sub
            End If
            Dim TuNgay As Integer
            Dim DenNgay As Integer
            Dim sNgayCuoiThang As String
            Dim sThang As String
            Dim DaysInMonth As Integer = DateTime.DaysInMonth(Nam.TenNam, Thang.TenThang)
            If DaysInMonth <= 9 Then
                sNgayCuoiThang = "0" & DaysInMonth.ToString()
            Else
                sNgayCuoiThang = DaysInMonth.ToString()
            End If
            If Integer.Parse(Thang.TenThang) <= 9 Then
                sThang = "0" & Thang.TenThang
            Else
                sThang = Thang.TenThang
            End If
            TuNgay = Integer.Parse(Nam.TenNam & sThang & "01")
            DenNgay = Integer.Parse(Nam.TenNam & sThang & sNgayCuoiThang)


            If RadioButton3.Checked Then
                TrangThai = "Tất cả"
            ElseIf RadioButton1.Checked Then
                TrangThai = "Chưa duyệt"
            ElseIf RadioButton2.Checked Then
                TrangThai = "Đã duyệt"
            ElseIf RadioButton4.Checked Then
                TrangThai = "Đã hủy"
            End If
            Dim TongTien As Single = 0
            Dim dtThongKe As List(Of DonHang)
            Dim controller As New DonHangBLL
            dtThongKe = controller.DonHangBan_GetItems(TrangThai, TuNgay, DenNgay)
            Dim sThanhTien As String
            For i As Integer = 0 To dtThongKe.Count - 1
                formatDate2VN(dtThongKe(i).NgayBan)
                TongTien = TongTien + dtThongKe(i).TongTien
                sThanhTien = CDec(dtThongKe(i).TongTien.ToString).ToString("N", Globalization.CultureInfo.CreateSpecificCulture("vi-vn")).ToString()
                dtThongKe(i).DoanhThu = sThanhTien
            Next
            lblSum.Text = CDec(TongTien.ToString).ToString("N", Globalization.CultureInfo.CreateSpecificCulture("vi-vn")).ToString()
            dgvKhachHang.AutoGenerateColumns = False
            dgvKhachHang.DataSource = dtThongKe
            If dgvKhachHang.Rows.Count - 1 > 0 Then
                dgvKhachHang.Rows(0).Selected = True
            End If
        End Sub
#End Region
#Region "Report theo năm"
        Sub Report_TheoNam()
            Dim TrangThai As String = ""
            Dim Nam As YearInfo
            Nam = CType(cbxTheoNam.SelectedItem, YearInfo)
            If Nam Is Nothing Then
                MessageBox.Show("Bạn chưa chọn năm.Vui lòng kiểm tra lại!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Sub
            End If
            Dim TuNgay As Integer = Integer.Parse(Nam.TenNam & "01" & "01")
            Dim DenNgay As Integer = Integer.Parse(Nam.TenNam & "12" & "30")
            If RadioButton3.Checked Then
                TrangThai = "Tất cả"
            ElseIf RadioButton1.Checked Then
                TrangThai = "Chưa duyệt"
            ElseIf RadioButton2.Checked Then
                TrangThai = "Đã duyệt"
            ElseIf RadioButton4.Checked Then
                TrangThai = "Đã hủy"
            End If
            Dim TongTien As Single = 0
            Dim dtThongKe As List(Of DonHang)
            Dim controller As New DonHangBLL
            dtThongKe = controller.DonHangBan_GetItems(TrangThai, TuNgay, DenNgay)
            Dim sThanhTien As String
            For i As Integer = 0 To dtThongKe.Count - 1
                formatDate2VN(dtThongKe(i).NgayBan)
                TongTien = TongTien + dtThongKe(i).TongTien
                sThanhTien = CDec(dtThongKe(i).TongTien.ToString).ToString("N", Globalization.CultureInfo.CreateSpecificCulture("vi-vn")).ToString()
                dtThongKe(i).DoanhThu = sThanhTien
            Next
            lblSum.Text = CDec(TongTien.ToString).ToString("N", Globalization.CultureInfo.CreateSpecificCulture("vi-vn")).ToString()
            dgvKhachHang.AutoGenerateColumns = False
            dgvKhachHang.DataSource = dtThongKe
            If dgvKhachHang.Rows.Count - 1 > 0 Then
                dgvKhachHang.Rows(0).Selected = True
            End If
        End Sub
#End Region
#Region "Report từ ngày đến ngày"
        Sub Report_TuNgayDenNgay()
            '2010007004  -->20100704
            Dim TuNgay As Integer = ConvertDateToInt(dtpTuNgay.Value.ToString.Split(" ")(0))
            Dim DenNgay As Integer = ConvertDateToInt(dtpDenNgay.Value.ToString.Split(" ")(0))
            If DenNgay < TuNgay Then
                Dim dlgRes As DialogResult
                dlgRes = MessageBox.Show( _
                          "Ngày đến không thể nhỏ hơn từ ngày.Vui lòng nhập lại", _
                          "Thông báo", _
                    MessageBoxButtons.OK, _
                          MessageBoxIcon.Question)
                If dlgRes = Windows.Forms.DialogResult.OK Then
                    Exit Sub
                End If
            End If
            Dim TrangThai As String = ""
            If RadioButton3.Checked Then
                TrangThai = "Tất cả"
            ElseIf RadioButton1.Checked Then
                TrangThai = "Chưa duyệt"
            ElseIf RadioButton2.Checked Then
                TrangThai = "Đã duyệt"
            ElseIf RadioButton4.Checked Then
                TrangThai = "Đã hủy"
            End If
            Dim TongTien As Single = 0
            Dim dtThongKe As List(Of DonHang)
            Dim controller As New DonHangBLL
            dtThongKe = controller.DonHangBan_GetItems(TrangThai, TuNgay, DenNgay)
            Dim sThanhTien As String
            For i As Integer = 0 To dtThongKe.Count - 1
                formatDate2VN(dtThongKe(i).NgayBan)
                TongTien = TongTien + dtThongKe(i).TongTien
                sThanhTien = CDec(dtThongKe(i).TongTien.ToString).ToString("N", Globalization.CultureInfo.CreateSpecificCulture("vi-vn")).ToString()
                dtThongKe(i).DoanhThu = sThanhTien
            Next
            lblSum.Text = CDec(TongTien.ToString).ToString("N", Globalization.CultureInfo.CreateSpecificCulture("vi-vn")).ToString()
            dgvKhachHang.AutoGenerateColumns = False
            dgvKhachHang.DataSource = dtThongKe
            If dgvKhachHang.Rows.Count - 1 > 0 Then
                dgvKhachHang.Rows(0).Selected = True
            End If
        End Sub
#End Region
#Region "Report theo tên khách hàng"
        REM Tìm kiếm tên khách hàng
        Private MaKhachHang As String
        Sub KhachHang_Search()
            Try
                Dim dbConn As New OleDb.OleDbConnection
                Dim dataAccess As New DataAccess
                Dim dsKhachHang As New DataSet
                Dim dtKhachHang As New DataTable
                Dim query As String = "Select KhachHangId,MaKhachHang,TenKhachHang,SoDienThoai,DiaChi From DanhMucKhachHang Where Xoa=0 And TenKhachHang Like N'%" & txtTenKhachHang_Search.Text.Trim & "%'"
                Dim adapter As OleDb.OleDbDataAdapter
                dataAccess.ConnectDatabase_DBAccess(dbConn)
                adapter = New OleDb.OleDbDataAdapter(query, dbConn)
                adapter.Fill(dsKhachHang)
                dbConn.Close()
                dtKhachHang = dsKhachHang.Tables(0)
                Panel_KhachHang_Search.Visible = True
                dgvKhachHang_Search.AutoGenerateColumns = False
                dgvKhachHang_Search.DataSource = dtKhachHang
                Panel_KhachHang_Search.BringToFront()
            Catch ex As Exception
                MessageBox.Show(ex.ToString())
            End Try
        End Sub

        Private Sub txtTenKhachHang_Search_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtTenKhachHang_Search.KeyDown
            Try
                If e.KeyCode = Keys.Enter Then
                    txtTenKhachHang_Search.Text = dgvKhachHang_Search.Rows(dgvKhachHang_Search.CurrentCell.RowIndex).Cells("TenKhachHang_S").Value.ToString()
                    Panel_KhachHang_Search.Visible = False
                    cmdThongKe.Focus()
                End If
            Catch ex As Exception

            End Try
        End Sub

        Private Sub txtTenKhachHang_Search_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtTenKhachHang_Search.KeyUp
            Try
                If txtTenKhachHang_Search.Text <> "" Then
                    KhachHang_Search()
                    If e.KeyCode = Keys.Up Or e.KeyCode = Keys.Down Then
                        dgvKhachHang_Search.Focus()
                    End If
                Else
                    Panel_KhachHang_Search.Visible = False
                End If
            Catch ex As Exception
                MessageBox.Show(ex.ToString())
            End Try
        End Sub
        Private Sub dgvKhachHang_Search_CellDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvKhachHang_Search.CellDoubleClick
            Try
                txtTenKhachHang_Search.Text = dgvKhachHang_Search.Rows(e.RowIndex).Cells("TenKhachHang_S").Value.ToString()
                MaKhachHang = dgvKhachHang_Search.Rows(e.RowIndex).Cells("KhachHangId_ThongKe").Value.ToString()
                Panel_KhachHang_Search.Visible = False
                cmdThongKe.Focus()
            Catch ex As Exception

            End Try
        End Sub

        Private Sub cmdThongKe_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdThongKe.Enter
            Try
                Panel_KhachHang_Search.Visible = False
            Catch ex As Exception

            End Try
        End Sub
        Sub Report_TenKhachHang()
            Dim TenKhacHang As String = txtTenKhachHang_Search.Text
            Dim TrangThai As String = ""
            If RadioButton3.Checked Then
                TrangThai = "Tất cả"
            ElseIf RadioButton1.Checked Then
                TrangThai = "Chưa duyệt"
            ElseIf RadioButton2.Checked Then
                TrangThai = "Đã duyệt"
            ElseIf RadioButton4.Checked Then
                TrangThai = "Đã hủy"
            End If
            Dim TongTien As Single = 0
            Dim dtThongKe As List(Of DonHang)
            Dim controller As New DonHangBLL
            dtThongKe = controller.DonHangBan_GetItems_TenKhachHang(TrangThai, TenKhacHang)
            Dim sThanhTien As String
            For i As Integer = 0 To dtThongKe.Count - 1
                formatDate2VN(dtThongKe(i).NgayBan)
                TongTien = TongTien + dtThongKe(i).TongTien
                sThanhTien = CDec(dtThongKe(i).TongTien.ToString).ToString("N", Globalization.CultureInfo.CreateSpecificCulture("vi-vn")).ToString()
                dtThongKe(i).DoanhThu = sThanhTien
            Next
            lblSum.Text = CDec(TongTien.ToString).ToString("N", Globalization.CultureInfo.CreateSpecificCulture("vi-vn")).ToString()
            dgvKhachHang.AutoGenerateColumns = False
            dgvKhachHang.DataSource = dtThongKe
            If dgvKhachHang.Rows.Count - 1 > 0 Then
                dgvKhachHang.Rows(0).Selected = True
            End If
        End Sub
        Sub Report_SoHoaDon()
            Dim SoHoaDon As String = txtSoHoaDon.Text.Trim
            Dim TrangThai As String = ""
            If RadioButton3.Checked Then
                TrangThai = "Tất cả"
            ElseIf RadioButton1.Checked Then
                TrangThai = "Chưa duyệt"
            ElseIf RadioButton2.Checked Then
                TrangThai = "Đã duyệt"
            ElseIf RadioButton4.Checked Then
                TrangThai = "Đã hủy"
            End If
            Dim TongTien As Single = 0
            Dim dtThongKe As List(Of DonHang)
            Dim controller As New DonHangBLL
            dtThongKe = controller.DonHangBan_GetItems_SoHoaDon(TrangThai, SoHoaDon)
            Dim sThanhTien As String
            For i As Integer = 0 To dtThongKe.Count - 1
                formatDate2VN(dtThongKe(i).NgayBan)
                TongTien = TongTien + dtThongKe(i).TongTien
                sThanhTien = CDec(dtThongKe(i).TongTien.ToString).ToString("N", Globalization.CultureInfo.CreateSpecificCulture("vi-vn")).ToString()
                dtThongKe(i).DoanhThu = sThanhTien
            Next
            lblSum.Text = CDec(TongTien.ToString).ToString("N", Globalization.CultureInfo.CreateSpecificCulture("vi-vn")).ToString()
            dgvKhachHang.AutoGenerateColumns = False
            dgvKhachHang.DataSource = dtThongKe
            If dgvKhachHang.Rows.Count - 1 > 0 Then
                dgvKhachHang.Rows(0).Selected = True
            End If
        End Sub
#End Region










#Region "Load Data"
        Public Sub NguyenLieu_Load()
            'Dim dbConn As New OleDb.OleDbConnection
            'Dim dataAccess As New DataAccess
            'Dim dsLoaiSanPham As New DataSet
            'Dim dtLoaiSanPham As New DataTable
            ''Dim query As String = "Select NL.IdNguyenLieu,NL.TenNguyenLieu,NL.DonGia,DVT.TenDonVi From NguyenLieu as NL Left Outer Join DonViTinh as DVT on NL.IDDonVi = DVT.IDDonVi  Where IDLoai=" & cbxLoaisanpham.SelectedValue
            'Dim adapter As OleDb.OleDbDataAdapter
            'dataAccess.ConnectDatabase_DBAccess(dbConn)
            ''adapter = New OleDb.OleDbDataAdapter(query, dbConn)
            'adapter.Fill(dsLoaiSanPham)
            'dbConn.Close()
            ''cbxNguyenLieu.DataSource = dsLoaiSanPham.Tables(0)
            ''cbxNguyenLieu.DisplayMember = "TenNguyenLieu"
            ''cbxNguyenLieu.ValueMember = "IdNguyenLieu"
            'IsLoaded = True
        End Sub
#End Region
#Region "Util"
        Function PhatSinhMaHopDong() As String
            Dim random As New Random
            Dim MaHopDong As String = "HD-" & Now.Day & "-" & Now.Month & "-" & Now.Year & "-" & random.Next(1000, 9999)
            Return MaHopDong
        End Function

        'Function ConvertCurencyToInt(ByVal Curency As String) As Integer
        '    Dim retInt As Integer
        '    Curency = Curency.Split(",")(0).Replace(".", "")
        '    retInt = Integer.Parse(Curency)
        '    Return retInt
        'End Function
#End Region



        'Private Sub dgvSanPhamHopdong_Tab1_CellLeave(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvSanPhamHopdong_Tab1.CellLeave
        '    Try
        '        Select Case e.ColumnIndex
        '            Case 4
        '                If IsDBNull(dgvSanPhamHopdong_Tab1.CurrentCell.Value) And (Not IsDBNull(dgvSanPhamHopdong_Tab1(1, dgvSanPhamHopdong_Tab1.CurrentCell.RowIndex))) Then
        '                    dgvSanPhamHopdong_Tab1.CurrentCell.Value = "0.00"
        '                End If
        '            Case 5
        '                If dgvSanPhamHopdong_Tab1.CurrentCell.Value = ""(Not IsDBNull(dgvSanPhamHopdong_Tab1(1, dgvSanPhamHopdong_Tab1.CurrentCell.RowIndex))) Then
        '                    dgvSanPhamHopdong_Tab1.CurrentCell.Value = "0.00"
        '                End If
        '        End Select
        '    Catch ex As Exception

        '    End Try
        'End Sub


        'Private Sub dgvSanPhamHopdong_Tab1_CellMouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles dgvSanPhamHopdong_Tab1.CellMouseClick
        '    RowEditIndex = e.RowIndex
        'End Sub
        'Private Sub dgvSanPhamHopdong_CellBeginEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellCancelEventArgs) Handles dgvSanPhamHopdong.CellBeginEdit
        '    Me.ControlBox = False
        'End Sub
        'Private Sub dgvSanPhamHopdong_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvSanPhamHopdong.CellEndEdit
        '    'disable close form
        '    Dim IDSanPham As Integer = Integer.Parse(dgvSanPhamHopdong.Rows(e.RowIndex).Cells("IDSanPham").Value.ToString)
        '    Dim SoLuong As String = dgvSanPhamHopdong.Rows(e.RowIndex).Cells("SoLuong").Value.ToString
        '    Dim DonGia As String = dgvSanPhamHopdong.Rows(e.RowIndex).Cells("DonGia").Value.ToString
        '    Dim ThanhTien As String
        '    'check format
        '    If IsNumeric(SoLuong) Then
        '        Try
        '            Dim rowUpdate() As DataRow
        '            rowUpdate = dtSanPhamHD.Select("IDSanPham=" & IDSanPham)
        '            If rowUpdate.Length > 0 Then
        '                rowUpdate(0).Item("SoLuong") = (Integer.Parse(SoLuong) + Integer.Parse(rowUpdate(0).Item("SoLuong"))).ToString()
        '                ThanhTien = Integer.Parse(SoLuong) * ConvertCurencyToInt(DonGia)
        '                rowUpdate(0).Item("ThanhTien") = CDec(ThanhTien).ToString("N", Globalization.CultureInfo.CreateSpecificCulture("vi-vn"))
        '                dtSanPhamHD.AcceptChanges()
        '                dgvSanPhamHopdong.Rows(e.RowIndex).Cells("ThanhTien").Value = ThanhTien
        '            End If
        '        Catch ex As Exception
        '            Dim dlgRes As DialogResult
        '            dlgRes = MessageBox.Show( _
        '          "Kiểu dữ liệu bạn nhập chưa đúng.Vui lòng kiểm tra lại", _
        '          "Thông báo", _
        '    MessageBoxButtons.OK, _
        '          MessageBoxIcon.Question)
        '            If dlgRes = Windows.Forms.DialogResult.OK Then
        '                Exit Sub
        '            End If
        '        End Try
        '    End If
        'End Sub




        Private Sub HuyBo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
            IsEdit = False
            'txtSoLuong.Text = ""
            'cmdThemSanPham.Text = "Thêm sản phẩm"
        End Sub
        Private Sub XuatHoaDon()
            'frmInHoaDon.IDKhachHang = IDKhachHang_Max
            frmInHoaDon.Show()
        End Sub

        'Function ConvertDateToInt(ByVal Ngay As String)
        '    Dim aNgay As String() = Ngay.Split("/")
        '    'Dim iThang As String
        '    'Dim iNgay As String
        '    Dim Ngay_So As String
        '    'If Integer.Parse(aNgay(1)) <= 9 Then
        '    '    iNgay = "0" & aNgay(1)
        '    'Else
        '    '    iNgay = aNgay(1)
        '    'End If
        '    'If Integer.Parse(aNgay(0)) <= 9 Then
        '    '    iThang = "0" & aNgay(0)
        '    'Else
        '    '    iThang = aNgay(0)
        '    'End If
        '    Ngay_So = aNgay(2) & aNgay(0) & aNgay(1)
        '    Try
        '        Return Integer.Parse(Ngay_So)
        '    Catch ex As Exception
        '        Return 0
        '    End Try
        'End Function

        'Tab 2
        Sub DisableControl()
            dtpTheoNgay.Enabled = False
            cbxTheoThang.Enabled = False
            cbxNamTheoThang.Enabled = False
            cbxTheoNam.Enabled = False
            dtpTuNgay.Enabled = False
            dtpDenNgay.Enabled = False
            txtSoHoaDon.Enabled = False
        End Sub

        Private Sub rbtTheoNgay_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rbtTheoNgay.CheckedChanged
            DisableControl()
            dtpTheoNgay.Enabled = True
            ReportType = 0
        End Sub
        Private IsPostBack As Boolean = False
        Private Sub rbtTheoThang_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rbtTheoThang.CheckedChanged
            DisableControl()
            cbxTheoThang.Enabled = True
            cbxNamTheoThang.Enabled = True
            If IsPostBack = False Then
                cbxTheoThang.SelectedIndex = IndexCurrentMonth
            End If
            cbxNamTheoThang.Enabled = True
            If IsPostBack = False Then
                cbxNamTheoThang.SelectedIndex = 0
            End If
            ReportType = 1
            IsPostBack = True
        End Sub
        Private IsPostBack2 As Boolean = False
        Private Sub rbtTheoNam_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rbtTheoNam.CheckedChanged
            DisableControl()
            cbxTheoNam.Enabled = True
            If IsPostBack2 = False Then
                cbxTheoNam.SelectedIndex = 0
            End If
            ReportType = 2
            IsPostBack2 = True
        End Sub

        Private Sub rbtTuNgay_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rbtTuNgay.CheckedChanged
            DisableControl()
            dtpTuNgay.Enabled = True
            dtpDenNgay.Enabled = True
            ReportType = 3
        End Sub
        Private Sub rbtTenKhachHang_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rbtTenKhachHang.CheckedChanged
            DisableControl()
            txtTenKhachHang_Search.Enabled = True
            ReportType = 4
        End Sub
        Private Sub rbtSoHoaDon_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles rbtSoHoaDon.CheckedChanged
            DisableControl()
            txtSoHoaDon.Enabled = True
            ReportType = 5
        End Sub
        Public Sub KhachHang_Load()
            Select Case ReportType
                Case 0
                    Report_TheoNgay()
                Case 1
                    Report_TheoThang()
                Case 2
                    Report_TheoNam()
                Case 3
                    Report_TuNgayDenNgay()
                Case 4
                    Report_TenKhachHang()
                Case 5
                    Report_SoHoaDon()
            End Select
        End Sub
        Private Sub cmdThongKe_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdThongKe.Click
            Try
                lblUpdate.Visible = True
                Cursor.Current = Cursors.WaitCursor
                Select Case ReportType
                    Case 0
                        Report_TheoNgay()
                    Case 1
                        Report_TheoThang()
                    Case 2
                        Report_TheoNam()
                    Case 3
                        Report_TuNgayDenNgay()
                    Case 4
                        Report_TenKhachHang()
                    Case 5
                        Report_SoHoaDon()
                End Select
                lblUpdate.Visible = False
                Cursor.Current = Cursors.Default
            Catch ex As Exception
                ShowDonHang(ex)
            End Try
        End Sub
        Function ConvertCurencyToInt(ByVal Curency As String) As Single
            Dim retInt As Single
            Curency = Curency.Split(",")(0).Replace(".", "")
            retInt = Single.Parse(Curency)
            Return retInt
        End Function
        Sub TinhTienHoaDon(ByRef TongTien As String, ByVal IDKhachHang As String)
            Try
                Dim dbConn As New OleDb.OleDbConnection
                Dim dataAccess As New DataAccess
                Dim dsTongTien As New DataSet
                Dim dtTongTien As New DataTable
                Dim query_Tien_HoaDon As String
                Dim adapter As OleDb.OleDbDataAdapter
                Dim TongTienHoaDon As Integer = 0
                query_Tien_HoaDon = String.Format("Select ThanhTien From HoaDon Where IDKhachHang={0}", IDKhachHang)
                dataAccess.ConnectDatabase_DBAccess(dbConn)
                adapter = New OleDb.OleDbDataAdapter(query_Tien_HoaDon, dbConn)
                adapter.Fill(dsTongTien)
                dtTongTien = dsTongTien.Tables(0)
                For i As Integer = 0 To dtTongTien.Rows.Count - 1
                    dtTongTien.Rows(i)("ThanhTien") = cm.Decrypt(dtTongTien.Rows(i)("ThanhTien"))
                    TongTienHoaDon = TongTienHoaDon + ConvertCurencyToInt(dtTongTien.Rows(i)("ThanhTien"))
                Next
                TongTien = CDec(TongTienHoaDon.ToString).ToString("N", Globalization.CultureInfo.CreateSpecificCulture("vi-vn")).ToString()
            Catch ex As Exception
                MessageBox.Show("Có lỗi trong quá trình xử lý.Vui lòng thử lại")
            End Try
        End Sub


        'Function ConvertDateToInt(ByVal Ngay As String)
        '    Dim aNgay As String() = Ngay.Split("/")
        '    'Dim iThang As String
        '    'Dim iNgay As String
        '    Dim Ngay_So As String
        '    'If Integer.Parse(aNgay(1)) <= 9 Then
        '    '    iNgay = aNgay(1)
        '    'Else
        '    '    iNgay = aNgay(1)
        '    'End If
        '    'If Integer.Parse(aNgay(0)) <= 9 Then
        '    '    iThang = "0" & aNgay(0)
        '    'Else
        '    '    iThang = aNgay(0)
        '    'End If
        '    Ngay_So = aNgay(2) & aNgay(0) & aNgay(1)
        '    Try
        '        Return Integer.Parse(Ngay_So)
        '    Catch ex As Exception
        '        Return 0
        '    End Try
        'End Function


        Function formatDate_VN(ByRef Ngay As String) As Boolean
            Dim aNgay As String() = Ngay.Split("/")
            Ngay = aNgay(1) & "/" & aNgay(0) & "/" & aNgay(2)
        End Function
        Function Format_ThanhToan(ByRef ThanhToan As String, Optional ByVal TienTamUng As String = "") As Boolean
            Select Case ThanhToan
                Case "0"
                    ThanhToan = "Chưa thanh toán"
                Case "1"
                    If TienTamUng = "0,00" Then
                        ThanhToan = "Thanh toán chưa thu tiền"
                    Else
                        ThanhToan = "Thanh toán đã tạm ứng"
                    End If
                Case "2"
                    ThanhToan = "Thanh toán đã thu tiền"
                Case "3"
                    ThanhToan = "Chưa nhập nguyên liệu"
            End Select
        End Function
        Private Sub dgvKhachHang_CellMouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles dgvKhachHang.CellMouseClick
            RowEditIndex = e.RowIndex
        End Sub
#Region "Load data"
        Private Sub Nam_Load()
            Dim currentYear As Integer = Now.Year
            cbxTheoNam.Items.Clear()
            Try
                While (currentYear >= 2011)
                    cbxTheoNam.Items.Add(New YearInfo(currentYear, currentYear.ToString))
                    cbxNamTheoThang.Items.Add(New YearInfo(currentYear, currentYear.ToString))
                    currentYear = currentYear - 1
                End While
            Catch ex As Exception
                Throw ex
            End Try
        End Sub
        Private Sub Thang_Load()
            Dim currentYear As Integer = 1
            cbxTheoThang.Items.Clear()
            Try
                Dim i As Integer = 0
                While (currentYear <= 12)
                    cbxTheoThang.Items.Add(New MonthInfo(currentYear, currentYear.ToString))
                    If currentYear = Now.Month Then
                        IndexCurrentMonth = i
                    End If
                    currentYear = currentYear + 1
                    i = i + 1
                End While
            Catch ex As Exception
                Throw ex
            End Try
        End Sub
#End Region
#Region "Sub Class"
        Private Class YearInfo
            Dim _Nam As Integer
            Dim _TenNam As String
            Public Sub New(ByVal Nam As Integer, ByVal TenNam As String)
                _Nam = Nam
                _TenNam = TenNam
            End Sub
            Public Function Nam() As Integer
                Return _Nam
            End Function
            Public Function TenNam() As String
                Return _TenNam
            End Function
            Public Overrides Function ToString() As String
                Return _TenNam
            End Function
        End Class
        Private Class MonthInfo
            Dim _Thang As Integer
            Dim _TenThang As String
            Public Sub New(ByVal Thang As Integer, ByVal TenThang As String)
                _Thang = Thang
                _TenThang = TenThang
            End Sub
            Public Function Thang() As Integer
                Return _Thang
            End Function
            Public Function TenThang() As String
                Return _TenThang
            End Function
            Public Overrides Function ToString() As String
                Return _TenThang
            End Function
        End Class
#End Region

        Private Sub InHoaDon_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
            Dim IdDonHangBan As Integer = Integer.Parse(dgvKhachHang.Rows(dgvKhachHang.CurrentCell.RowIndex).Cells("IdDonHangBan").Value.ToString)
            frmInHoaDon.IdDonHangBan = IdDonHangBan
            frmInHoaDon.Show()

        End Sub

        'Private Sub Xoa_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Xoa.Click
        '    Dim IDKhachHang As Integer = Integer.Parse(dgvKhachHang.Rows(RowEditIndex).Cells("IDKhachHang").Value.ToString)
        '    Dim dlgRes As DialogResult
        '    dlgRes = MessageBox.Show( _
        '              "Bạn muốn xóa thông tin khách hàng này", _
        '              "Thông báo", _
        '        MessageBoxButtons.OKCancel, _
        '              MessageBoxIcon.Question)
        '    If dlgRes = Windows.Forms.DialogResult.OK Then
        '        Dim query As String = String.Format("Delete From KhachHang Where IDKhachHang={0}", IDKhachHang)
        '        Dim dbConn As New OleDb.OleDbConnection
        '        Dim connectAccess As New DataAccess
        '        Dim dbCommand As OleDb.OleDbCommand
        '        connectAccess.ConnectDatabase_DBAccess(dbConn)
        '        dbCommand = New OleDb.OleDbCommand(query, dbConn)
        '        dbCommand.ExecuteNonQuery()
        '        dbConn.Close()
        '        Select Case ReportType
        '            Case 0
        '                Report_TheoNgay()
        '            Case 1
        '                Report_TheoThang()
        '            Case 2
        '                Report_TheoNam()
        '            Case 3
        '                Report_TuNgayDenNgay()
        '        End Select
        '    End If
        'End Sub

        Private Sub MenuDuyetDonHang_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
            Try
                Dim IDDonHangBan As Integer = Integer.Parse(dgvKhachHang.Rows(dgvKhachHang.CurrentCell.RowIndex).Cells("IDDonHangBan").Value.ToString)
                'check tình trạng, nếu đơn hàng đã duyệt thì không thể xóa

                Dim dbConn As New OleDb.OleDbConnection
                Dim dataAccess As New DataAccess
                Dim query As String
                dataAccess.ConnectDatabase_DBAccess(dbConn)
                Dim TrangThai As String = ""
                Dim dbCommand As OleDb.OleDbCommand
                query = "Select TrangThai From DonHangBan Where IdDonHangBan=" & IDDonHangBan
                dbCommand = New OleDbCommand(query, dbConn)
                TrangThai = dbCommand.ExecuteScalar()
                If TrangThai = "Đã duyệt" Then
                    MessageBox.Show("Đơn hàng đã được duyệt.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Hand)
                    dbConn.Close()
                    Exit Sub
                End If
                Dim dlgRes As DialogResult
                dlgRes = MessageBox.Show( _
                          "Bạn đồng ý duyệt đơn hàng này?", _
                          "Thông báo", _
                    MessageBoxButtons.OKCancel, _
                          MessageBoxIcon.Question)
                If dlgRes = Windows.Forms.DialogResult.OK Then
                    query = String.Format("Update DonHangBan Set TrangThai=N'Đã duyệt' Where IDDonHangBan={0};Update ChiTietDonHangBan Set TrangThai=N'Đã duyệt' Where IDDonHangBan={0}", IDDonHangBan)
                    dbCommand = New OleDb.OleDbCommand(query, dbConn)
                    dbCommand.ExecuteNonQuery()
                    '----------Cập nhật số lượng tồn kho----------------
                    query = "Select IdSanPham,SoLuong From ChiTietDonHangBan Where LoaiPhi='HangHoa' And IDDonHangBan=" & IDDonHangBan
                    Dim dtSoLuongSP As New DataTable
                    Dim adapter As OleDb.OleDbDataAdapter
                    adapter = New OleDb.OleDbDataAdapter(query, dbConn)
                    adapter.Fill(dtSoLuongSP)
                    Dim SoLuongTru As Integer
                    For i As Integer = 0 To dtSoLuongSP.Rows.Count - 1
                        SoLuongTru = Integer.Parse(dtSoLuongSP.Rows(i)("SoLuong"))
                        query = "Update SanPham Set SoLuongTon = SoLuongTon - " & SoLuongTru & " Where IdSanPham=" & dtSoLuongSP.Rows(i)("IDSanPham")
                        dbCommand = New OleDbCommand(query, dbConn)
                        dbCommand.ExecuteNonQuery()
                    Next
                    dbConn.Close()
                    '
                    If txtTenKhachHang_Search.Text = "" Then
                        rbtTheoNgay.Checked = True
                        DisableControl()
                        dtpTheoNgay.Enabled = True
                        Nam_Load()
                        Thang_Load()
                        Report_TheoNgay()
                    Else
                        Select Case ReportType
                            Case 0
                                Report_TheoNgay()
                            Case 1
                                Report_TheoThang()
                            Case 2
                                Report_TheoNam()
                            Case 3
                                Report_TuNgayDenNgay()
                            Case Else
                                Report_TenKhachHang()
                        End Select
                    End If
                End If
            Catch ex As Exception

            End Try
        End Sub

        Private Sub ThanhToanDaThuTien_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
            Try

                Dim IDKhachHang As Integer = Integer.Parse(dgvKhachHang.Rows(RowEditIndex).Cells("IDKhachHang").Value.ToString)
                Dim dbConn As New OleDbConnection
                Dim connectDatabase As New DataAccess
                Dim dbCommand As OleDbCommand
                Dim TinhTrangThanhToan As String
                Dim query_TinhTrang_KhachHang As String = String.Format("Select ThanhToan From KhachHang Where IDKhachHang={0}", IDKhachHang)
                connectDatabase.ConnectDatabase_DBAccess(dbConn)
                dbCommand = New OleDbCommand(query_TinhTrang_KhachHang, dbConn)
                TinhTrangThanhToan = dbCommand.ExecuteScalar
                Select Case TinhTrangThanhToan
                    Case "0"
                        'kiem tra tinh trang khach hang neu la 0 thi cap nhat kho va cap nhat tinh trang len 2
                        Dim query_SanPham_HoaDon As String
                        Dim adapter As OleDbDataAdapter
                        Dim dsSanPhamHoaDon As New DataSet
                        Dim dtSanPhamHoaDon As New DataTable
                        'lấy tất cả các sản phầm trong hóa đơn
                        query_TinhTrang_KhachHang = String.Format("Select ThanhToan From KhachHang Where IDKhachHang={0}", IDKhachHang)
                        'khoi tao ket noi
                        dbCommand = New OleDbCommand(query_TinhTrang_KhachHang, dbConn)
                        TinhTrangThanhToan = Integer.Parse(dbCommand.ExecuteScalar().ToString)
                        query_SanPham_HoaDon = String.Format("Select IDSanPham,SoLuong,Ngay From HoaDon Where IDKhachHang={0}", IDKhachHang)
                        adapter = New OleDbDataAdapter(query_SanPham_HoaDon, dbConn)
                        adapter.Fill(dsSanPhamHoaDon)
                        dtSanPhamHoaDon = dsSanPhamHoaDon.Tables(0)
                        Dim IDSanPham As Integer
                        Dim SoLuongTruKho As Single
                        Dim Ngay As String
                        Dim Thang As Integer
                        Dim Nam As Integer
                        For i As Integer = 0 To dtSanPhamHoaDon.Rows.Count - 1
                            Dim query_TruKho As String
                            IDSanPham = dtSanPhamHoaDon.Rows(i)("IDSanPham")
                            SoLuongTruKho = cm.Decrypt(dtSanPhamHoaDon.Rows(i)("SoLuong"))
                            Ngay = cm.Decrypt(dtSanPhamHoaDon.Rows(i)("Ngay"))
                            Thang = Integer.Parse(Ngay.Split("/")(0))
                            Nam = Integer.Parse(Ngay.Split("/")(2))
                            query_TruKho = String.Format("Update NguyenLieu Set SoLuong=SoLuong - {0} Where IDNguyenLieu={1}", SoLuongTruKho, IDSanPham)
                            dbCommand = New OleDbCommand(query_TruKho, dbConn)
                            dbCommand.ExecuteNonQuery()
                            'luu vao bang khovatlieu nhap/xuat
                            'lay ten nguyen lieu
                            Dim dsNguyenLieu_Info As New DataSet
                            Dim dtNguyenLieu_Info As New DataTable
                            Dim query_NguyenLieuInfo As String = String.Format("Select TenNguyenLieu,DonGia From NguyenLieu Where IDNguyenLieu={0}", IDSanPham)
                            Dim adapter_NguyenLieu As OleDbDataAdapter
                            Dim TenNguyenLieu As String
                            Dim DonGiaNguyenLieu As String
                            adapter_NguyenLieu = New OleDbDataAdapter(query_NguyenLieuInfo, dbConn)
                            adapter_NguyenLieu.Fill(dsNguyenLieu_Info)
                            dtNguyenLieu_Info = dsNguyenLieu_Info.Tables(0)
                            TenNguyenLieu = dtNguyenLieu_Info.Rows(0)("TenNguyenLieu")
                            DonGiaNguyenLieu = dtNguyenLieu_Info.Rows(0)("DonGia")
                            Dim query_khovatlieu_xuat As String
                            'kiem tra ngay nay , nguyen lieu nay da xuat chua neu chua thi insert nguoc lai thi update
                            Dim query_khovatlieu_nguyenlieu As String
                            query_khovatlieu_nguyenlieu = String.Format("Select count(*) From KhoVatLieu Where IDNguyenLieu={0} And NhapXuat=0 And Ngay='{1}'", IDSanPham, Ngay)
                            dbCommand = New OleDbCommand(query_khovatlieu_nguyenlieu, dbConn)
                            Dim result As Integer = dbCommand.ExecuteScalar()
                            If result > 0 Then
                                Dim SoLuongHienTai As Single
                                Dim query_SoLuongHienTai As String = "Select SoLuong From KhoVatLieu Where IDSanPham=" & IDSanPham & " And Ngay='" & dtSanPhamHoaDon.Rows(i)("Ngay") & "'"
                                dbCommand = New OleDbCommand(query_SoLuongHienTai, dbConn)
                                SoLuongHienTai = Single.Parse(cm.Decrypt(dbCommand.ExecuteScalar()))
                                Dim SoLuongUpdate As String
                                SoLuongUpdate = cm.Encrypt((SoLuongHienTai + SoLuongTruKho).ToString)
                                query_khovatlieu_xuat = String.Format("Update KhoVatLieu Set SoLuong=SoLuong + {0} Where IDNguyenLieu={1} And Ngay='{2}' And NhapXuat=0", SoLuongUpdate, IDSanPham, Ngay)
                            Else
                                query_khovatlieu_xuat = "Insert Into KhoVatLieu(IDNguyenLieu,TenNguyenLieu,DonGia,NhapXuat,SoLuong,Ngay,Thang,Nam) Values(" & IDSanPham & ",'" & cm.Encrypt(TenNguyenLieu) & "','" & cm.Encrypt(DonGiaNguyenLieu) & "',0,'" & cm.Encrypt(SoLuongTruKho) & "','" & cm.Encrypt(Ngay) & "','" & cm.Encrypt(Thang) & "','" & cm.Encrypt(Nam) & "')"
                            End If
                            dbCommand = New OleDbCommand(query_khovatlieu_xuat, dbConn)
                            dbCommand.ExecuteNonQuery()
                        Next
                        Dim DaThanhToanDu As String = cm.Encrypt("Đã thanh toán đủ")
                        query_TinhTrang_KhachHang = String.Format("Update KhachHang Set ThanhToan=2,TienTamUng='" & DaThanhToanDu & "' Where IDKhachHang={0}", IDKhachHang)
                        dbCommand = New OleDbCommand(query_TinhTrang_KhachHang, dbConn)
                        dbCommand.ExecuteNonQuery()
                    Case "1"
                        Dim DaThanhToanDu As String = cm.Encrypt("Đã thanh toán đủ")
                        'neu la 1 thi chi cap nhat len 2
                        query_TinhTrang_KhachHang = String.Format("Update KhachHang Set ThanhToan=2,TienTamUng='" & DaThanhToanDu & "' Where IDKhachHang={0}", IDKhachHang)
                        dbCommand = New OleDbCommand(query_TinhTrang_KhachHang, dbConn)
                        dbCommand.ExecuteNonQuery()
                End Select
                dbConn.Close()
                'cap nhat lai grid
                Select Case ReportType
                    Case 0
                        Report_TheoNgay()
                    Case 1
                        Report_TheoThang()
                    Case 2
                        Report_TheoNam()
                    Case 3
                        Report_TuNgayDenNgay()
                    Case 4
                        Report_TenKhachHang()
                End Select
            Catch ex As Exception
                MessageBox.Show("Có lỗi trong quá trình cập nhật")
            End Try
        End Sub





        Public Sub ShowModal(ByVal Frm As Form, Optional ByVal MinimumBox As Boolean = True, Optional ByVal MaximumBox As Boolean = True)
            Frm.MaximizeBox = MaximumBox
            Frm.MinimizeBox = MinimumBox
            CenterForm(Frm)
            Frm.ShowDialog()
        End Sub
        Public Sub CenterForm(ByVal Frm As Form)
            Frm.StartPosition = FormStartPosition.CenterScreen
        End Sub




        Private Sub cmdXoaThongTin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdXoaThongTin.Click
            Try
                Order_Clear()
                IsViewHistory = False
            Catch ex As Exception

            End Try
        End Sub
        Private Sub txtTimKiem_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
            Try
                NguyenLieu_TimKiem()
            Catch ex As Exception

            End Try
        End Sub
        Public Sub NguyenLieu_TimKiem()
            'Dim dbConn As New OleDb.OleDbConnection
            'Dim dataAccess As New DataAccess
            'Dim dsLoaiSanPham As New DataSet
            'Dim dtLoaiSanPham As New DataTable
            ''Dim query As String = "Select NL.IdNguyenLieu,NL.TenNguyenLieu,NL.DonGia,DVT.TenDonVi From NguyenLieu as NL Left Outer Join DonViTinh as DVT on NL.IDDonVi = DVT.IDDonVi  Where IDLoai=" & cbxLoaisanpham.SelectedValue & " And NL.TenNguyenLieu Like '%" & txtSanPham.Text & "%'"
            'Dim adapter As OleDb.OleDbDataAdapter
            'dataAccess.ConnectDatabase_DBAccess(dbConn)
            'adapter = New OleDb.OleDbDataAdapter(query, dbConn)
            'adapter.Fill(dsLoaiSanPham)
            'dbConn.Close()
            'cbxNguyenLieu.DataSource = dsLoaiSanPham.Tables(0)
            'cbxNguyenLieu.DisplayMember = "TenNguyenLieu"
            'cbxNguyenLieu.ValueMember = "IdNguyenLieu"
            IsLoaded = True
        End Sub

        Private Sub cmdDong_SearchKhachHang_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdDong_SearchKhachHang.Click
            Try
                Panel_KhachHang.Visible = False
            Catch ex As Exception

            End Try
        End Sub

        Private Sub cmdDong_SearchSanPham_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
            Try
                'Panel_SanPham.Visible = False
            Catch ex As Exception

            End Try
        End Sub

        Private Sub cmdDong_KhachHangTab2Search_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdDong_KhachHangTab2Search.Click
            Try
                Panel_KhachHang_Search.Visible = False

            Catch ex As Exception

            End Try
        End Sub

        Private Sub TabPage1_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdXemThongTinChiTiet.Enter
            txtTenKhachHang_Search.Text = ""
        End Sub
        Private Sub TabPage2_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles TabPage2.Enter
            Panel_KhachHang.Visible = False
        End Sub
        Private Sub cmdHuyDonHang_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdHuyDonHang.Click
            Try
                Dim IDDonHangBan As Integer = Integer.Parse(dgvKhachHang.Rows(dgvKhachHang.CurrentCell.RowIndex).Cells("IDDonHangBan").Value.ToString)
                Dim RowSelected As Integer = dgvKhachHang.CurrentCell.RowIndex
                Dim dlgRes As DialogResult
                dlgRes = MessageBox.Show( _
                          "Bạn đồng ý hủy đơn hàng này?", _
                          "Thông báo", _
                    MessageBoxButtons.OKCancel, _
                          MessageBoxIcon.Question)
                If dlgRes = Windows.Forms.DialogResult.OK Then
                    'Hủy Đơn Hàng
                    Dim dbConn As New OleDb.OleDbConnection
                    Dim dataAccess As New DataAccess
                    Dim dbCommand As OleDb.OleDbCommand
                    dataAccess.ConnectDatabase_DBAccess(dbConn)
                    dbCommand = New OleDbCommand("spDonHangBan_HuyDonHang", dbConn)
                    dbCommand.CommandType = CommandType.StoredProcedure
                    dbCommand.Parameters.Add("@IDDonHangBan", OleDbType.VarWChar).Value = IDDonHangBan
                    dbCommand.Parameters.Add("@NgayHuy", OleDbType.VarWChar).Value = NgayTao()
                    dbCommand.Parameters.Add("@NguoiHuy", OleDbType.VarWChar).Value = NguoiTao()
                    dbCommand.ExecuteNonQuery()
                    dbConn.Close()
                    Select Case ReportType
                        Case 0
                            Report_TheoNgay()
                        Case 1
                            Report_TheoThang()
                        Case 2
                            Report_TheoNam()
                        Case 3
                            Report_TuNgayDenNgay()
                        Case 4
                            Report_TenKhachHang()
                        Case 5
                            Report_SoHoaDon()
                    End Select
                    'Sroll To Row SelecteddgvSanPhamRight.FirstDisplayedScrollingRowIndex = i
                    dgvKhachHang.FirstDisplayedScrollingRowIndex = RowSelected
                    dgvKhachHang.CurrentCell = dgvKhachHang(1, RowSelected)
                End If
            Catch ex As Exception
                ShowError(ex)
            End Try
        End Sub
        Private Sub cmdKeThuaDonHang_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdKeThuaDonHang.Click
            'Kiểm Tra Đơn Hàng Đã Hủy Bỏ Chưa|Nếu Chưa Hủy Bỏ Thì Thông Báo
            Try
                Dim IDDonHangBan As Integer = Integer.Parse(dgvKhachHang.Rows(dgvKhachHang.CurrentCell.RowIndex).Cells("IDDonHangBan").Value.ToString)
                'Hủy Đơn Hàng
                Dim TrangThai As String
                Dim dbConn As New OleDb.OleDbConnection
                Dim dataAccess As New DataAccess
                Dim dbCommand As OleDb.OleDbCommand
                dataAccess.ConnectDatabase_DBAccess(dbConn)
                dbCommand = New OleDbCommand("spDonHangBan_TrangThai", dbConn)
                dbCommand.CommandType = CommandType.StoredProcedure
                dbCommand.Parameters.Add("@IDDonHangBan", OleDbType.VarWChar).Value = IDDonHangBan
                TrangThai = dbCommand.ExecuteScalar()
                dbConn.Close()
                If TrangThai = "Đã hủy" Then
                    Order_KeThua()
                Else
                    MessageBox.Show("Đơn hàng chưa được hủy.Vui lòng hủy đơn hàng trước khi chỉnh sửa đơn hàng.", "Thông báo", MessageBoxButtons.OK)
                End If
            Catch ex As Exception
                ShowError(ex)
            End Try
        End Sub
        Private Sub cmdEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdEdit.Click
            'Kiểm Tra Đơn Hàng Đã Hủy Bỏ Chưa|Nếu Chưa Hủy Bỏ Thì Thông Báo
            Try
                Dim IDDonHangBan As Integer = Integer.Parse(dgvKhachHang.Rows(dgvKhachHang.CurrentCell.RowIndex).Cells("IDDonHangBan").Value.ToString)
                'Hủy Đơn Hàng
                Dim TrangThai As String
                Dim dbConn As New OleDb.OleDbConnection
                Dim dataAccess As New DataAccess
                Dim dbCommand As OleDb.OleDbCommand
                dataAccess.ConnectDatabase_DBAccess(dbConn)
                dbCommand = New OleDbCommand("spDonHangBan_TrangThai", dbConn)
                dbCommand.CommandType = CommandType.StoredProcedure
                dbCommand.Parameters.Add("@IDDonHangBan", OleDbType.VarWChar).Value = IDDonHangBan
                TrangThai = dbCommand.ExecuteScalar()
                dbConn.Close()
                If TrangThai = "Đã hủy" Then
                    Order_Edit()
                Else
                    MessageBox.Show("Đơn hàng chưa được hủy.Vui lòng hủy đơn hàng trước khi chỉnh sửa đơn hàng.", "Thông báo", MessageBoxButtons.OK)
                End If
            Catch ex As Exception
                ShowError(ex)
            End Try
            'IsViewHistory = False'      
        End Sub

        Private Sub cmdDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdDelete.Click
            Try
                Dim IDDonHangBan As Integer = Integer.Parse(dgvKhachHang.Rows(dgvKhachHang.CurrentCell.RowIndex).Cells("IDDonHangBan").Value.ToString)
                'Hủy Đơn Hàng
                Dim TrangThai As String
                Dim dbConn As New OleDb.OleDbConnection
                Dim dataAccess As New DataAccess
                Dim dbCommand As OleDb.OleDbCommand
                dataAccess.ConnectDatabase_DBAccess(dbConn)
                dbCommand = New OleDbCommand("spDonHangBan_TrangThai", dbConn)
                dbCommand.CommandType = CommandType.StoredProcedure
                dbCommand.Parameters.Add("@IDDonHangBan", OleDbType.VarWChar).Value = IDDonHangBan
                TrangThai = dbCommand.ExecuteScalar()
                Dim dlgRes As DialogResult
                If TrangThai = "Đã hủy" Then
                    dlgRes = MessageBox.Show( _
                          "Bạn muốn xóa thông tin đơn hàng này.", _
                              "Thông báo", _
                        MessageBoxButtons.OKCancel, _
                              MessageBoxIcon.Question)
                    If dlgRes = Windows.Forms.DialogResult.OK Then
                        Dim query As String = String.Format("Update DonHangBan Set Xoa=1,NgayXoa='{0}',NguoiXoa='{1}' Where IDDonHangBan={2};Update ChiTietDonHangBan Set Xoa=1,NgayXoa='{3}',NguoiXoa='{4}' Where IDDonHangBan={5}", NgayTao, NguoiTao, IDDonHangBan, NgayTao, NguoiTao, IDDonHangBan)
                        dbCommand = New OleDb.OleDbCommand(query, dbConn)
                        dbCommand.ExecuteNonQuery()
                        dbConn.Close()
                        Select Case ReportType
                            Case 0
                                Report_TheoNgay()
                            Case 1
                                Report_TheoThang()
                            Case 2
                                Report_TheoNam()
                            Case 3
                                Report_TuNgayDenNgay()
                            Case Else
                                Report_TenKhachHang()
                        End Select
                    End If
                Else
                    MessageBox.Show("Đơn hàng chưa được hủy.Vui lòng hủy đơn hàng trước khi xóa đơn hàng.", "Thông báo", MessageBoxButtons.OK)
                    dbConn.Close()
                End If
            Catch ex As Exception
                ShowError(ex)
            End Try
        End Sub

        Private Sub cmdPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdPrint.Click
            Dim IdDonHangBan As Integer = Integer.Parse(dgvKhachHang.Rows(dgvKhachHang.CurrentCell.RowIndex).Cells("IdDonHangBan").Value.ToString)
            frmInHoaDon.IdDonHangBan = IdDonHangBan
            frmInHoaDon.Show()
        End Sub

        Private Sub cmdAproved_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAproved.Click
            Try
                Dim IDDonHangBan As Integer = Integer.Parse(dgvKhachHang.Rows(dgvKhachHang.CurrentCell.RowIndex).Cells("IDDonHangBan").Value.ToString)
                'check tình trạng, nếu đơn hàng đã duyệt thì không thể xóa

                Dim dbConn As New OleDb.OleDbConnection
                Dim dataAccess As New DataAccess
                Dim query As String
                dataAccess.ConnectDatabase_DBAccess(dbConn)
                Dim TrangThai As String = ""
                Dim dbCommand As OleDb.OleDbCommand
                query = "Select TrangThai From DonHangBan Where IdDonHangBan=" & IDDonHangBan
                dbCommand = New OleDbCommand(query, dbConn)
                TrangThai = dbCommand.ExecuteScalar()
                If TrangThai = "Đã duyệt" Then
                    MessageBox.Show("Đơn hàng đã được duyệt.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Hand)
                    dbConn.Close()
                    Exit Sub
                End If
                Dim dlgRes As DialogResult
                dlgRes = MessageBox.Show( _
                          "Bạn đồng ý duyệt đơn hàng này?", _
                          "Thông báo", _
                    MessageBoxButtons.OKCancel, _
                          MessageBoxIcon.Question)
                If dlgRes = Windows.Forms.DialogResult.OK Then
                    query = String.Format("Update DonHangBan Set TrangThai=N'Đã duyệt' Where IDDonHangBan={0};Update ChiTietDonHangBan Set TrangThai=N'Đã duyệt' Where IDDonHangBan={0}", IDDonHangBan)
                    dbCommand = New OleDb.OleDbCommand(query, dbConn)
                    dbCommand.ExecuteNonQuery()
                    '----------Cập nhật số lượng tồn kho----------------
                    query = "Select IdSanPham,SoLuong From ChiTietDonHangBan Where LoaiPhi='HangHoa' And IDDonHangBan=" & IDDonHangBan
                    Dim dtSoLuongSP As New DataTable
                    Dim adapter As OleDb.OleDbDataAdapter
                    adapter = New OleDb.OleDbDataAdapter(query, dbConn)
                    adapter.Fill(dtSoLuongSP)
                    Dim SoLuongTru As Single
                    For i As Integer = 0 To dtSoLuongSP.Rows.Count - 1
                        SoLuongTru = Single.Parse(dtSoLuongSP.Rows(i)("SoLuong"))
                        query = "Update SanPham Set SoLuongTon = SoLuongTon - " & SoLuongTru & " Where IdSanPham=" & dtSoLuongSP.Rows(i)("IDSanPham")
                        dbCommand = New OleDbCommand(query, dbConn)
                        dbCommand.ExecuteNonQuery()
                    Next
                    dbConn.Close()
                    '
                    Select Case ReportType
                        Case 0
                            Report_TheoNgay()
                        Case 1
                            Report_TheoThang()
                        Case 2
                            Report_TheoNam()
                        Case 3
                            Report_TuNgayDenNgay()
                        Case Else
                            Report_TenKhachHang()
                    End Select
                End If
            Catch ex As Exception

            End Try
        End Sub


        '--duyet
        Private Sub RadioButton2_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadioButton2.CheckedChanged
            Select Case ReportType
                Case 0
                    Report_TheoNgay()
                Case 1
                    Report_TheoThang()
                Case 2
                    Report_TheoNam()
                Case 3
                    Report_TuNgayDenNgay()
                Case 4
                    Report_TenKhachHang()
                Case 5
                    Report_SoHoaDon()
            End Select
        End Sub
        '--chưa duyet
        Private Sub RadioButton1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadioButton1.CheckedChanged
            Select Case ReportType
                Case 0
                    Report_TheoNgay()
                Case 1
                    Report_TheoThang()
                Case 2
                    Report_TheoNam()
                Case 3
                    Report_TuNgayDenNgay()
                Case 4
                    Report_TenKhachHang()
                Case 5
                    Report_SoHoaDon()
            End Select
        End Sub
        '---tat ca
        Private Sub RadioButton3_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadioButton3.CheckedChanged
            Select Case ReportType
                Case 0
                    Report_TheoNgay()
                Case 1
                    Report_TheoThang()
                Case 2
                    Report_TheoNam()
                Case 3
                    Report_TuNgayDenNgay()
                Case 4
                    Report_TenKhachHang()
                Case 5
                    Report_SoHoaDon()
            End Select
        End Sub
        Private Sub RadioButton4_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadioButton4.CheckedChanged
            Select Case ReportType
                Case 0
                    Report_TheoNgay()
                Case 1
                    Report_TheoThang()
                Case 2
                    Report_TheoNam()
                Case 3
                    Report_TuNgayDenNgay()
                Case 4
                    Report_TenKhachHang()
                Case 5
                    Report_SoHoaDon()
            End Select
        End Sub
        'Private Sub dgvGiamTru_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs)
        '    Try
        '        For i As Integer = 0 To dgvGiamTru.RowCount - 1
        '            If dgvGiamTru("MucTruHoaDonId", i).Value >= 10000 Then
        '                dgvGiamTru.Rows(i).DefaultCellStyle.BackColor = Color.FromArgb(255, 224, 192)
        '            End If
        '        Next
        '    Catch ex As Exception

        '    End Try
        'End Sub




        Private Sub dgvSanPhamHopdong_Tab1_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles dgvSanPhamHopdong_Tab1.EditingControlShowing
            Try
                Dim MaSanPham As New TextBox
                Dim cboEdit As New DataGridViewComboBoxEditingControl
                If dgvSanPhamHopdong_Tab1.CurrentCell.ColumnIndex = 1 Then
                    MaSanPham = CType(e.Control, TextBox)
                    MaSanPham.AutoCompleteMode = AutoCompleteMode.SuggestAppend
                    MaSanPham.AutoCompleteSource = AutoCompleteSource.CustomSource
                    MaSanPham.AutoCompleteCustomSource = aMaSanPham
                ElseIf dgvSanPhamHopdong_Tab1.CurrentCell.ColumnIndex = 4 Then
                    If TypeOf (e.Control) Is DataGridViewComboBoxEditingControl Then
                        cboEdit = CType(e.Control, DataGridViewComboBoxEditingControl)
                        cboEdit.DropDownStyle = ComboBoxStyle.DropDown
                        cboEdit.AutoCompleteMode = AutoCompleteMode.None
                        AddHandler cboEdit.Validating, AddressOf cbo_Validating
                    End If
                    MaSanPham.AutoCompleteMode = AutoCompleteMode.None
                    MaSanPham.AutoCompleteSource = AutoCompleteSource.None
                Else
                    MaSanPham = CType(e.Control, TextBox)
                    MaSanPham.AutoCompleteMode = AutoCompleteMode.None
                    MaSanPham.AutoCompleteSource = AutoCompleteSource.None
                End If
                'AddHandler MaSanPham.KeyUp, AddressOf CellKeyUp
                'AddHandler MaSanPham.KeyPress, AddressOf CellKeyPress
                AddHandler MaSanPham.Leave, AddressOf CellKeyLeave
                AddHandler MaSanPham.Validating, AddressOf CellValidating
            Catch ex As Exception

            End Try
        End Sub
        Private Sub cbo_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs)
            Try
                Dim newPrice As String
                Dim listPrice As New List(Of String)
                Dim cbo As DataGridViewComboBoxEditingControl
                cbo = CType(sender, DataGridViewComboBoxEditingControl)
                newPrice = cbo.Text
                Dim comboxPrice As DataGridViewComboBoxCell
                comboxPrice = CType(dgvSanPhamHopdong_Tab1("DonGia", dgvSanPhamHopdong_Tab1.CurrentCell.RowIndex), DataGridViewComboBoxCell)
                listPrice = comboxPrice.DataSource
                If Not listPrice.Contains(newPrice) Then
                    listPrice = New List(Of String)
                    listPrice.Add(newPrice)
                    comboxPrice.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing
                    comboxPrice.DataSource = listPrice
                    comboxPrice.Value = newPrice
                End If

            Catch ex As Exception

            End Try
        End Sub
        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Xử lý sự kiện chỉ cho nhập số cho cell DonGia va SoLuong
        ''' </summary>
        ''' <remarks>
        ''' 
        ''' </remarks>
        ''' <history>
        '''   [lamtn] 18/02/2011  Created
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Private Sub CellKeyLeave(ByVal sender As Object, ByVal e As System.EventArgs)
            Try
                Dim ColumnIndex As Integer = dgvSanPhamHopdong_Tab1.CurrentCell.ColumnIndex
                Dim RowIndex As Integer = dgvSanPhamHopdong_Tab1.CurrentCell.RowIndex
                Select Case ColumnIndex
                    Case 1
                        AddProductManual()
                        'Case 4
                        'Dim newPrice As String = dgvSanPhamHopdong_Tab1(ColumnIndex, RowIndex).Value
                        '    'Kiểm Tra Nếu Rỗng Thì Set Về 0.00
                        '    'FormatNumberCell(dgvSanPhamHopdong_Tab1.CurrentCell)
                    Case 5
                        ''Trường hợp nhập số lượng
                        If dgvSanPhamHopdong_Tab1(5, dgvSanPhamHopdong_Tab1.CurrentCell.RowIndex).Value <> "" Then
                            KiemTraSoLuongTon()
                        End If
                End Select
            Catch ex As Exception
                ShowError(ex)
            End Try
        End Sub
        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Xử lý sự kiện khi thay đổi đơn giá và số lượng thì tính toán lại thành tiền
        ''' </summary>
        ''' <remarks>
        ''' 
        ''' </remarks>
        ''' <history>
        '''   [lamtn] 18/02/2011  Created
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Private Sub dgvSanPhamHopdong_Tab1_CellValueChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvSanPhamHopdong_Tab1.CellValueChanged
            Try
                If e.RowIndex >= 0 Then
                    If e.ColumnIndex = 4 Or e.ColumnIndex = 5 Then
                        'fix speed
                        Dim comboPrice As DataGridViewComboBoxCell
                        Dim DonGia As Double
                        Dim SoLuong As Single
                        comboPrice = CType(dgvSanPhamHopdong_Tab1(4, e.RowIndex), DataGridViewComboBoxCell)
                        DonGia = IIf(comboPrice.EditedFormattedValue = "", 0, comboPrice.EditedFormattedValue)
                        If dgvSanPhamHopdong_Tab1(5, e.RowIndex).Value = "" Then
                            SoLuong = 0
                        Else
                            SoLuong = dgvSanPhamHopdong_Tab1(5, e.RowIndex).Value
                        End If
                        'fix ThanhTien Tien: USD, VND, SGD
                        Dim ThanhTien As Double
                        Dim LoaiPhi As String = dgvSanPhamHopdong_Tab1(7, e.RowIndex).Value
                        Dim TienHang As Double = 0
                        Dim TienGiamTru As Double = 0
                        Dim TongTien As Double = 0
                        For i As Integer = 0 To dgvSanPhamHopdong_Tab1.Rows.Count - 1
                            Dim IDSanPham As Integer = Integer.Parse(dgvSanPhamHopdong_Tab1("IDSanPham", i).Value)
                            Dim LoaiPhiHH As String = dgvSanPhamHopdong_Tab1("LoaiPhi", i).Value
                            If IDSanPham > 0 And LoaiPhiHH = "HangHoa" Then
                                comboPrice = CType(dgvSanPhamHopdong_Tab1("DonGia", i), DataGridViewComboBoxCell)
                                'Lam Tron
                                Dim DonGiaHH As Double
                                'Dim DonGiaHH As Integer = comboPrice.EditedFormattedValue
                                DonGiaHH = comboPrice.EditedFormattedValue
                                Dim SoLuongHH As Integer = IIf(dgvSanPhamHopdong_Tab1("SoLuong", i).Value = "", 0, dgvSanPhamHopdong_Tab1("SoLuong", i).Value)
                                TienHang = TienHang + Double.Parse(DonGiaHH) * Single.Parse(SoLuongHH)
                            End If
                        Next
                        If LoaiPhi = "GiamTru" And DonGia <= 100 Then
                            'fix ThanhTien Tien: USD, VND, SGD
                            If comboTien.SelectedValue = "VND" Then
                                ThanhTien = LamTron((DonGia * SoLuong * TienHang) / 100, 0)
                            ElseIf comboTien.SelectedValue = "USD" Or comboTien.SelectedValue = "SGD" Then
                                ThanhTien = LamTron((DonGia * SoLuong * TienHang) / 100, 2)
                            End If
                        Else
                            If comboTien.SelectedValue = "VND" Then
                                ThanhTien = LamTron(DonGia * SoLuong, 0)
                            ElseIf comboTien.SelectedValue = "USD" Or comboTien.SelectedValue = "SGD" Then
                                ThanhTien = LamTron(DonGia * SoLuong, 2)
                            End If
                        End If
                        dgvSanPhamHopdong_Tab1(6, e.RowIndex).Value = ThanhTien.ToString("N02", US)
                        '----Tinh Lai Thong Tien Hang
                        'fix ThanhTien Tien: USD, VND, SGD
                        'Dim ThanhTienHangHoa As Integer = 0
                        Dim ThanhTienHangHoa As Double = 0
                        For i As Integer = 0 To dgvSanPhamHopdong_Tab1.Rows.Count - 1
                            Dim IDSanPham As Integer = Integer.Parse(dgvSanPhamHopdong_Tab1("IDSanPham", i).Value)
                            LoaiPhi = dgvSanPhamHopdong_Tab1("LoaiPhi", i).Value
                            'fix ThanhTien Tien: USD, VND, SGD
                            'Dim iThanhTien As Integer
                            Dim iThanhTien As Double
                            If IDSanPham > 0 And LoaiPhi = "HangHoa" Then
                                iThanhTien = dgvSanPhamHopdong_Tab1("ThanhTien", i).Value
                                ThanhTienHangHoa = ThanhTienHangHoa + iThanhTien
                            End If
                        Next
                        '----Tinh Lai Tong Giam Tru Theo Phan Tram
                        'fix ThanhTien Tien: USD, VND, SGD
                        'Dim ThanhTienGiamTru As Integer = 0
                        Dim ThanhTienGiamTru As Double = 0
                        For i As Integer = 0 To dgvSanPhamHopdong_Tab1.Rows.Count - 1
                            Dim IDSanPham As Integer = Integer.Parse(dgvSanPhamHopdong_Tab1("IDSanPham", i).Value)
                            Dim LoaiPhiHH As String = dgvSanPhamHopdong_Tab1("LoaiPhi", i).Value
                            If IDSanPham > 0 And LoaiPhiHH = "GiamTru" Then
                                comboPrice = CType(dgvSanPhamHopdong_Tab1("DonGia", i), DataGridViewComboBoxCell)
                                Dim DonGiaHH As Double = comboPrice.Value
                                Dim SoLuongHH As Single = dgvSanPhamHopdong_Tab1("SoLuong", i).Value
                                If DonGiaHH <= 100 Then
                                    'Khoản giảm trừ tính theo phần trăm
                                    If comboTien.SelectedValue = "VND" Then
                                        ThanhTienGiamTru = LamTron((DonGiaHH * SoLuongHH * ThanhTienHangHoa) / 100, 0)
                                    ElseIf comboTien.SelectedValue = "USD" Or comboTien.SelectedValue = "SGD" Then
                                        ThanhTienGiamTru = LamTron((DonGiaHH * SoLuongHH * ThanhTienHangHoa) / 100, 2)
                                    End If
                                    dgvSanPhamHopdong_Tab1(6, i).Value = ThanhTienGiamTru.ToString("N02", US)
                                End If
                            End If
                        Next
                        'Tinh Hang Chua Thue Moi Dung
                        TinhTienHangChuaThue()
                        TinhTienThueVAT()
                        TinhTienThueDaThue()
                    End If
                End If
                'end fix speed
            Catch ex As Exception
                ShowDonHang(ex)
            End Try
        End Sub
        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Thêm sản phẩm vào đơn hàng bằng cách nhập chính xác
        ''' </summary>
        ''' <remarks>
        ''' Cho nhập số lẻ
        ''' </remarks>
        ''' <history>
        '''   [lamtn] 18/02/2011  Created
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Private Sub KiemTraSoLuongTon()
            Try
                Dim dataAccess As New DataAccess
                Dim dbConn As New OleDb.OleDbConnection
                Dim dbCommand As OleDbCommand
                dataAccess.ConnectDatabase_DBAccess(dbConn)
                Dim ProductCode As String = dgvSanPhamHopdong_Tab1("MaHang", dgvSanPhamHopdong_Tab1.CurrentCell.RowIndex).Value
                Dim LoaiPhi As String = dgvSanPhamHopdong_Tab1("LoaiPhi", dgvSanPhamHopdong_Tab1.CurrentCell.RowIndex).Value
                If LoaiPhi = "HangHoa" Then
                    Dim query As String = "Select SoLuongTon From SanPham Where Xoa=0 And MaSanPham='" & ProductCode & "'"
                    dbCommand = New OleDbCommand(query, dbConn)
                    Dim SoLuongTon As Single
                    Dim SoLuongNhap As Single = dgvSanPhamHopdong_Tab1("SoLuong", dgvSanPhamHopdong_Tab1.CurrentCell.RowIndex).Value
                    If IsDBNull(dbCommand.ExecuteScalar()) Or String.IsNullOrEmpty(dbCommand.ExecuteScalar()) Then
                        SoLuongTon = 0
                    Else
                        SoLuongTon = dbCommand.ExecuteScalar()
                    End If
                    dbConn.Close()
                    Dim FontBold As New Font(dgvSanPhamHopdong_Tab1.Font, FontStyle.Bold)
                    Dim FondNormal As New Font(dgvSanPhamHopdong_Tab1.Font, FontStyle.Regular)
                    If SoLuongTon < SoLuongNhap Then
                        dgvSanPhamHopdong_Tab1("SoLuong", dgvSanPhamHopdong_Tab1.CurrentCell.RowIndex).Style.ForeColor = Color.Red
                        dgvSanPhamHopdong_Tab1("SoLuong", dgvSanPhamHopdong_Tab1.CurrentCell.RowIndex).Style.Font = FontBold
                    Else
                        dgvSanPhamHopdong_Tab1("SoLuong", dgvSanPhamHopdong_Tab1.CurrentCell.RowIndex).Style.ForeColor = Color.Black
                        dgvSanPhamHopdong_Tab1("SoLuong", dgvSanPhamHopdong_Tab1.CurrentCell.RowIndex).Style.Font = FondNormal
                    End If
                End If
            Catch ex As Exception
                ShowError()
            End Try
        End Sub
        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Thêm sản phẩm vào đơn hàng bằng cách nhập chính xác
        ''' </summary>
        ''' <remarks>
        ''' Cho nhập số lẻ
        ''' </remarks>
        ''' <history>
        '''   [lamtn] 18/02/2011  Created
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Private Sub AddProductManual()
            Try
                Dim dbConn As New OleDb.OleDbConnection
                Dim dataAccess As New DataAccess
                Dim dtProductDetail As New DataTable
                Dim ProductCode As String = dgvSanPhamHopdong_Tab1.CurrentCell.Value
                Dim RowIndex As Integer = dgvSanPhamHopdong_Tab1.CurrentCell.RowIndex
                Dim query As String = "Select  IDSanPham,TenSanPham,TenDonViTinh,DonGia From SanPham As SP " & _
                                        " Left Outer Join DVTSanPham AS DVT On SP.DVTSanPhamId=DVT.DVTSanPhamId " & _
                                        " Where SP.Xoa=0 And MaSanPham='" & ProductCode & "'"
                Dim adapter As OleDb.OleDbDataAdapter
                dataAccess.ConnectDatabase_DBAccess(dbConn)
                adapter = New OleDb.OleDbDataAdapter(query, dbConn)
                adapter.Fill(dtProductDetail)
                Dim listPrice As List(Of String)
                Dim comboxPrice As DataGridViewComboBoxCell
                Dim dtPrice As New DataTable
                If dtProductDetail.Rows.Count > 0 Then
                    dgvSanPhamHopdong_Tab1("IDSanPham", RowIndex).Value = dtProductDetail.Rows(0)("IDSanPham")
                    dgvSanPhamHopdong_Tab1("LoaiPhi", RowIndex).Value = "HangHoa"
                    dgvSanPhamHopdong_Tab1("TenHang", RowIndex).Value = dtProductDetail.Rows(0)("TenSanPham")
                    dgvSanPhamHopdong_Tab1("DonViTinh", RowIndex).Value = dtProductDetail.Rows(0)("TenDonViTinh")
                    'check if the products is many price
                    If (lblKhachHangId.Text <> "") Or (lblKhachHangId.Text = "0") Then
                        query = "Select DonGiaII From SanPhamNhieuGia Where IDKhachHang=" & lblKhachHangId.Text & " And IDSanPham=" & dtProductDetail.Rows(0)("IDSanPham")
                        adapter = New OleDb.OleDbDataAdapter(query, dbConn)
                        adapter.Fill(dtPrice)
                    End If
                    comboxPrice = CType(dgvSanPhamHopdong_Tab1("DonGia", RowIndex), DataGridViewComboBoxCell)
                    listPrice = New List(Of String)
                    listPrice.Add(dtProductDetail.Rows(0)("DonGia"))
                    If dtPrice.Rows.Count > 0 Then
                        For i As Integer = 0 To dtPrice.Rows.Count - 1
                            listPrice.Add(dtPrice.Rows(i)("DonGiaII"))
                        Next
                        comboxPrice.DisplayStyle = DataGridViewComboBoxDisplayStyle.ComboBox
                        comboxPrice.DataSource = listPrice
                        comboxPrice.Value = dtPrice.Rows(0)("DonGiaII")
                        dgvSanPhamHopdong_Tab1.CurrentRow.DefaultCellStyle.BackColor = Color.Aquamarine
                        dgvSanPhamHopdong_Tab1("IsManyPrice", RowIndex).Value = "1"
                    Else
                        comboxPrice.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing
                        comboxPrice.DataSource = listPrice
                        comboxPrice.Value = dtProductDetail.Rows(0)("DonGia")
                        dgvSanPhamHopdong_Tab1.CurrentRow.DefaultCellStyle.BackColor = Color.White
                        dgvSanPhamHopdong_Tab1("IsManyPrice", RowIndex).Value = "0"
                    End If
                    'fix speed edit
                    'dgvSanPhamHopdong_Tab1("SoLuong", RowIndex).Value = "0"
                    'dgvSanPhamHopdong_Tab1("ThanhTien", RowIndex).Value = "0"
                    Dim cellEdit As DataGridViewCell
                    cellEdit = dgvSanPhamHopdong_Tab1.CurrentRow.Cells("SoLuong")
                    dgvSanPhamHopdong_Tab1.CurrentCell = cellEdit
                    dgvSanPhamHopdong_Tab1.BeginEdit(True)
                Else
                    dgvSanPhamHopdong_Tab1("IDSanPham", RowIndex).Value = "0"
                    dgvSanPhamHopdong_Tab1("LoaiPhi", RowIndex).Value = ""
                    dgvSanPhamHopdong_Tab1("TenHang", RowIndex).Value = ""
                    dgvSanPhamHopdong_Tab1("DonViTinh", RowIndex).Value = ""
                    dgvSanPhamHopdong_Tab1("IsManyPrice", RowIndex).Value = ""
                    listPrice = New List(Of String)
                    listPrice.Add("")
                    comboxPrice = CType(dgvSanPhamHopdong_Tab1("DonGia", RowIndex), DataGridViewComboBoxCell)
                    comboxPrice.DataSource = listPrice
                    comboxPrice.Value = ""
                    'dgvSanPhamHopdong_Tab1("SoLuong", RowIndex).Value = "0"
                    'dgvSanPhamHopdong_Tab1("ThanhTien", RowIndex).Value = "0"
                End If
                dbConn.Close()
            Catch ex As Exception
                ShowDonHang(ex)
            End Try
        End Sub
        Private Sub AddProductSupportSearch()
            Try

            Catch ex As Exception

            End Try
        End Sub
        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Xử lý sự kiện chỉ cho nhập số cho cell DonGia va SoLuong 
        ''' </summary>
        ''' <remarks>
        ''' Cho nhập số lẻ
        ''' </remarks>
        ''' <history>
        '''   [lamtn] 18/02/2011  Created
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Private Sub CellKeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs)
            Try
                'If dgvSanPhamHopdong_Tab1.CurrentCell.ColumnIndex = 4 Then
                '    If e.KeyChar = "." Then
                '        e.Handled = False
                '    ElseIf Not Char.IsDigit(e.KeyChar) And Not Char.IsControl(e.KeyChar) Then
                '        e.Handled = True
                '    End If
                '    'If Not Char.IsLetterOrDigit(e.KeyChar) And Not Char.IsControl(e.KeyChar) Then
                '    '    e.Handled = True
                '    'End If
                'ElseIf dgvSanPhamHopdong_Tab1.CurrentCell.ColumnIndex = 5 Then
                '    If e.KeyChar = "." Then
                '        e.Handled = False
                '    ElseIf Not Char.IsDigit(e.KeyChar) And Not Char.IsControl(e.KeyChar) Then
                '        e.Handled = True
                '    End If
                '    'If Not Char.IsLetterOrDigit(e.KeyChar) And Not Char.IsControl(e.KeyChar) Then
                '    '    e.Handled = True
                '    'End If
                'End If
            Catch ex As Exception

            End Try

        End Sub
        Private Sub CellValidating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs)
            Try

            Catch ex As Exception

            End Try
        End Sub
        Private Function IsPrecent(ByVal txt As TextBox, ByVal c As Char) As Boolean
            Try
                If txt.Text = "" And c = "%" Then
                    Return False
                ElseIf txt.Text <> "" And c = "%" Then
                    If txt.Text.IndexOf("%") > 0 Then
                        Return False
                    End If
                End If
            Catch ex As Exception

            End Try
        End Function
        Private Function OnlyDot(ByVal c As TextBox) As Boolean
            Try
                Dim sRet As String = c.Text
                MessageBox.Show(sRet)
                Dim iPos As Integer = c.Text.IndexOf(".")
                If c.Text.IndexOf(".") > 0 Then
                    Return False
                Else
                    Return True
                End If
            Catch ex As Exception

            End Try
        End Function
        Private Function IsSingle(ByVal c As Char) As Boolean
            Try
                If Char.IsDigit(c) Then
                    Return True
                ElseIf c = "." Then
                    Return True
                Else
                    Return False
                End If
            Catch ex As Exception

            End Try
        End Function
        Private Sub CellKeyUp(ByVal sender As Object, ByVal e As KeyEventArgs)
            'Try
            '    Dim MaSanPham As TextBox = CType(sender, TextBox)
            '    'Get Current Location
            '    Dim newPoint As New Point
            '    newPoint.X = 58
            '    newPoint.Y = dgvSanPhamHopdong_Tab1.CurrentRow.Index * 22 + 188
            '    If newPoint.Y + 183 > 580 Then
            '        newPoint.Y = (newPoint.Y - 22) - 183
            '    End If
            '    Panel_SanPham.Location = newPoint
            '    If MaSanPham.Text <> "" Then
            '        'If dgvSanPhamHopdong_Tab1.PressF1Key Then
            '        '    Panel_MucTruHoaDon.Visible = True
            '        '    'Set Location
            '        '    'Get Current Location
            '        '    newPoint.X = 58
            '        '    newPoint.Y = dgvSanPhamHopdong_Tab1.CurrentRow.Index * 22 + 188
            '        '    If newPoint.Y + 183 > 580 Then
            '        '        newPoint.Y = (newPoint.Y - 22) - 183
            '        '    End If
            '        '    Panel_MucTruHoaDon.Location = newPoint
            '        '    dgvGiamTru.Focus()
            '        '    Panel_SanPham.Visible = False
            '        'Else
            '        '    If cbxSearchSupport.Checked Then
            '        '        If dgvSanPhamHopdong_Tab1.CurrentCell.ColumnIndex = 1 Then
            '        '            Panel_SanPham.Visible = True
            '        '            'Kiem Tra Xem Co Gia Uu Dai Ko
            '        '            Dim dbConn As New OleDb.OleDbConnection
            '        '            Dim dataAccess As New DataAccess
            '        '            Dim adapter As OleDb.OleDbDataAdapter
            '        '            dataAccess.ConnectDatabase_DBAccess(dbConn)
            '        '            'check xem khach hang nay co giam tru dc biet ko
            '        '            Dim query As String = "Select Count(*) As Total From SanPhamNhieuGia Where xoa=0 and IDKhachHang=" & IIf(lblKhachHangId.Text = "", "0", lblKhachHangId.Text)
            '        '            Dim dtCount As New DataTable
            '        '            adapter = New OleDb.OleDbDataAdapter(query, dbConn)
            '        '            adapter.Fill(dtCount)
            '        '            If dtCount.Rows(0)("Total") > 0 Then
            '        '                SanPhamTheoKhachHang_Load(MaSanPham.Text.Trim, lblKhachHangId.Text.Trim)
            '        '            Else
            '        '                SanPham_Load(MaSanPham.Text.Trim)
            '        '            End If
            '        '            dbConn.Close()
            '        '            Panel_MucTruHoaDon.Visible = False
            '        '        Else
            '        '            Panel_SanPham.Visible = False
            '        '        End If
            '        '    End If
            '        'End If
            '    Else
            '        'If dgvSanPhamHopdong_Tab1.PressF1Key Then
            '        '    Panel_MucTruHoaDon.Visible = True
            '        '    'Set Location
            '        '    'Get Current Location
            '        '    newPoint.X = 58
            '        '    newPoint.Y = dgvSanPhamHopdong_Tab1.CurrentRow.Index * 22 + 188
            '        '    If newPoint.Y + 183 > 580 Then
            '        '        newPoint.Y = (newPoint.Y - 22) - 183
            '        '    End If
            '        '    Panel_MucTruHoaDon.Location = newPoint
            '        '    dgvGiamTru.Focus()
            '        '    'Kiem Tra Xem Co Gia Uu Dai Ko
            '        '    Dim dbConn As New OleDb.OleDbConnection
            '        '    Dim dataAccess As New DataAccess
            '        '    Dim adapter As OleDb.OleDbDataAdapter
            '        '    dataAccess.ConnectDatabase_DBAccess(dbConn)
            '        '    'check xem khach hang nay co giam tru dc biet ko
            '        '    Dim query As String = "Select Count(*) As Total From MucTruHoaDonTheoKhachHang Where xoa=0 and KhachHangId=" & IIf(lblKhachHangId.Text = "", "0", lblKhachHangId.Text)
            '        '    Dim dtCount As New DataTable
            '        '    adapter = New OleDb.OleDbDataAdapter(query, dbConn)
            '        '    adapter.Fill(dtCount)
            '        '    If dtCount.Rows(0)("Total") > 0 Then
            '        '        GiamTruHoaDonTheoKhachHang(lblKhachHangId.Text.Trim)
            '        '    Else
            '        '        GiamTruHoaDon()
            '        '    End If
            '        '    dbConn.Close()
            '        '    Panel_SanPham.Visible = False
            '        '    dgvSanPhamHopdong_Tab1.PressF1Key = False
            '        'End If
            '    End If
            'Catch ex As Exception

            'End Try

        End Sub


        Private KeyEnterOnGridDetail As Boolean = False
        Private Sub dgvSanPham_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs)
            'Try
            '    Select Case e.KeyCode
            '        Case Keys.Down
            '        Case Keys.Up
            '        Case Keys.Escape
            '            Panel_SanPham.Visible = False
            '        Case Keys.Enter
            '            Dim IDSanPham As String
            '            Dim MaSanPham As String
            '            Dim TenSanPham As String
            '            Dim DonViTinh As String = ""
            '            Dim DonGia As String
            '            IDSanPham = dgvSanPham.CurrentRow.Cells(0).Value
            '            MaSanPham = dgvSanPham.CurrentRow.Cells(2).Value
            '            TenSanPham = dgvSanPham.CurrentRow.Cells(3).Value
            '            DonGia = dgvSanPham.CurrentRow.Cells(4).Value
            '            DonViTinh = dgvSanPham.CurrentRow.Cells(6).Value
            '            dgvSanPhamHopdong_Tab1.CurrentRow.Cells(0).Value = IDSanPham
            '            dgvSanPhamHopdong_Tab1.CurrentRow.Cells(1).Value = MaSanPham
            '            dgvSanPhamHopdong_Tab1.CurrentRow.Cells(2).Value = TenSanPham
            '            dgvSanPhamHopdong_Tab1.CurrentRow.Cells(3).Value = DonViTinh
            '            dgvSanPhamHopdong_Tab1.CurrentRow.Cells(4).Value = DonGia
            '            dgvSanPhamHopdong_Tab1.CurrentRow.Cells(7).Value = "HangHoa"
            '            Dim cellEdit As DataGridViewCell
            '            cellEdit = dgvSanPhamHopdong_Tab1.CurrentRow.Cells(5)
            '            dgvSanPhamHopdong_Tab1.CurrentCell = cellEdit
            '            dgvSanPhamHopdong_Tab1.BeginEdit(True)
            '            Panel_SanPham.Visible = False
            '            KeyEnterOnGridDetail = True
            '        Case Else
            '            dgvSanPhamHopdong_Tab1.Focus()
            '            Dim cell As DataGridViewCell
            '            cell = dgvSanPhamHopdong_Tab1.CurrentCell
            '            dgvSanPhamHopdong_Tab1.CurrentCell = cell
            '            dgvSanPhamHopdong_Tab1.BeginEdit(True)
            '    End Select
            'Catch ex As Exception

            'End Try
        End Sub
#Region "Làm mới lại form bán hàng"
#Region "Khởi tạo đơn hàng chỉ gồm có 15 dòng"
        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Khởi tạo đơn hàng cho phép nhập tối đa là 12 dòng
        ''' </summary>
        ''' <remarks>
        ''' 
        ''' </remarks>
        ''' <history>
        '''   [lamtn] 05/03/2011  Tạo
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Private Sub InitOrder()
            Try
                'dtSanPhamHD = CreateSanPhamHopDong()
                Dim dtOrder As New DataTable
                dtOrder = InitOrderTable()
                Dim newRow As DataRow
                For i As Integer = 0 To 11
                    newRow = dtOrder.NewRow
                    newRow.Item("RowIndex") = i + 1
                    newRow.Item("IDSanPham") = 0
                    newRow.Item("MaSanPham") = ""
                    newRow.Item("TenSanPham") = ""
                    newRow.Item("TenQuyCach") = ""
                    newRow.Item("SoLuong") = ""
                    newRow.Item("DonGia") = ""
                    newRow.Item("ThanhTien") = ""
                    newRow.Item("LoaiPhi") = ""
                    newRow.Item("IsManyPrice") = ""
                    dtOrder.Rows.Add(newRow)
                Next
                dgvSanPhamHopdong_Tab1.AutoGenerateColumns = False
                dgvSanPhamHopdong_Tab1.DataSource = dtOrder
            Catch ex As Exception
                Throw
            End Try
        End Sub
        Private Sub DeleteRow(ByVal RowDeleteIndex As Integer)
            Try
                'Save Temp
                Dim tempListProduct As New DataTable
                tempListProduct = InitOrderTable()
                Dim tempRow As DataRow
                Dim comboPrice As DataGridViewComboBoxCell
                Dim listPriceSource As New List(Of String)
                Dim listPrice As New List(Of String)
                Dim comboValue As String
                For i As Integer = 0 To 11
                    If i <> RowDeleteIndex Then
                        tempRow = tempListProduct.NewRow
                        tempRow.Item("IDSanPham") = dgvSanPhamHopdong_Tab1("IDSanPham", i).Value
                        tempRow.Item("MaSanPham") = dgvSanPhamHopdong_Tab1("MaHang", i).Value
                        tempRow.Item("TenSanPham") = dgvSanPhamHopdong_Tab1("TenHang", i).Value
                        tempRow.Item("TenQuyCach") = dgvSanPhamHopdong_Tab1("DonViTinh", i).Value
                        comboPrice = CType(dgvSanPhamHopdong_Tab1("DonGia", i), DataGridViewComboBoxCell)
                        listPriceSource = New List(Of String)
                        listPrice = New List(Of String)
                        If dgvSanPhamHopdong_Tab1("IsManyPrice", i).Value = "1" Then
                            'IsManyPrice
                            listPriceSource = comboPrice.DataSource
                            comboValue = comboPrice.EditedFormattedValue
                            listPriceSource.Remove(comboValue)
                            listPrice.Add(comboValue)
                            For j As Integer = 0 To listPriceSource.Count - 1
                                listPrice.Add(listPriceSource(j))
                            Next
                            For k As Integer = 0 To listPrice.Count - 1
                                If k = 0 Then
                                    tempRow.Item("DonGia") = listPrice(k).ToString()
                                Else
                                    tempRow.Item("DonGia") = tempRow.Item("DonGia") & "|" & listPrice(k).ToString()
                                End If
                            Next
                            tempRow.Item("IsManyPrice") = "1"
                        Else
                            'IsOnlyPrice
                            tempRow.Item("DonGia") = comboPrice.EditedFormattedValue
                            tempRow.Item("IsManyPrice") = "0"
                        End If
                        tempRow.Item("SoLuong") = dgvSanPhamHopdong_Tab1("SoLuong", i).Value
                        tempRow.Item("ThanhTien") = dgvSanPhamHopdong_Tab1("ThanhTien", i).Value
                        tempRow.Item("LoaiPhi") = dgvSanPhamHopdong_Tab1("LoaiPhi", i).Value
                        tempListProduct.Rows.Add(tempRow)
                    End If
                Next
                'Add Row Vua Bi DEL
                tempRow = tempListProduct.NewRow
                tempRow.Item("IDSanPham") = 0
                tempRow.Item("MaSanPham") = ""
                tempRow.Item("TenSanPham") = ""
                tempRow.Item("TenQuyCach") = ""
                tempRow.Item("DonGia") = ""
                tempRow.Item("SoLuong") = ""
                tempRow.Item("ThanhTien") = ""
                tempRow.Item("LoaiPhi") = ""
                tempRow.Item("IsManyPrice") = "0"
                tempListProduct.Rows.Add(tempRow)
                'Push to GridView
                'tempListProduct.DefaultView.Sort = "LoaiPhi DESC"
                'Bind Manual
                'Tính lại tổng tiền hàng
                Dim ThanhTienHangHoa As Double = 0
                Dim DonGia As Double
                Dim SoLuong As Integer
                For i As Integer = 0 To tempListProduct.Rows.Count - 1
                    Dim LoaiPhi As String = tempListProduct.Rows(i)("LoaiPhi")
                    If LoaiPhi = "HangHoa" Then
                        SoLuong = tempListProduct.Rows(i)("SoLuong")
                        If tempListProduct.Rows(i)("IsManyPrice") = "1" Then
                            DonGia = tempListProduct.Rows(i)("DonGia").ToString.Split("|")(0)
                        Else
                            DonGia = tempListProduct.Rows(i)("DonGia")
                        End If
                        ThanhTienHangHoa = ThanhTienHangHoa + DonGia * SoLuong
                    End If
                Next
                For Each dr As DataRow In tempListProduct.Rows
                    If dr("LoaiPhi") = "GiamTru" Then
                        DonGia = dr("DonGia")
                        SoLuong = dr("SoLuong")
                        If DonGia <= 100 Then
                            If comboTien.SelectedValue = "VND" Then
                                dr("ThanhTien") = LamTron((ThanhTienHangHoa * SoLuong * DonGia) / 100, 0)
                            ElseIf comboTien.SelectedValue = "USD" Or comboTien.SelectedValue = "SGD" Then
                                dr("ThanhTien") = LamTron((ThanhTienHangHoa * SoLuong * DonGia) / 100, 2)
                            End If
                        End If
                    End If
                Next
                'clear all
                'InitOrder()
                For i As Integer = 0 To 11
                    dgvSanPhamHopdong_Tab1("IDSanPham", i).Value = tempListProduct.Rows(i)("IDSanPham")
                    dgvSanPhamHopdong_Tab1("MaHang", i).Value = tempListProduct.Rows(i)("MaSanPham")
                    dgvSanPhamHopdong_Tab1("TenHang", i).Value = tempListProduct.Rows(i)("TenSanPham")
                    dgvSanPhamHopdong_Tab1("DonViTinh", i).Value = tempListProduct.Rows(i)("TenQuyCach")
                    If dgvSanPhamHopdong_Tab1("MaHang", i).Value <> "" Then
                        'strThanhTien = CDec(tempListProduct.Rows(i)("ThanhTien")).ToString("N1", Globalization.CultureInfo.CreateSpecificCulture("en-us"))
                        'Bind Lai Don Gia
                        'Dim listPrice As New List(Of String)
                        'Kiem Tra Xem Co Nhieu Gia Khong
                        listPrice = New List(Of String)
                        Dim comboxPrice As New DataGridViewComboBoxCell
                        comboxPrice = CType(dgvSanPhamHopdong_Tab1("DonGia", i), DataGridViewComboBoxCell)
                        If tempListProduct.Rows(i)("IsManyPrice") = "1" Then
                            'Nhieu Gia
                            Dim aPrice() As String = tempListProduct.Rows(i)("DonGia").ToString.Split("|")
                            For j As Integer = 0 To aPrice.Length - 1
                                listPrice.Add(aPrice(j))
                            Next
                            comboxPrice.DisplayStyle = DataGridViewComboBoxDisplayStyle.ComboBox
                            comboxPrice.DataSource = listPrice
                            comboxPrice.Value = aPrice(0)
                            dgvSanPhamHopdong_Tab1.Rows(i).DefaultCellStyle.BackColor = Color.Aquamarine
                        Else
                            'Mot Gia
                            listPrice.Add(tempListProduct.Rows(i)("DonGia"))
                            comboxPrice.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing
                            comboxPrice.DataSource = listPrice
                            comboxPrice.Value = tempListProduct.Rows(i)("DonGia")
                            dgvSanPhamHopdong_Tab1.Rows(i).DefaultCellStyle.BackColor = Color.White
                        End If
                        dgvSanPhamHopdong_Tab1("IsManyPrice", i).Value = tempListProduct.Rows(i)("IsManyPrice")
                        dgvSanPhamHopdong_Tab1("SoLuong", i).Value = tempListProduct.Rows(i)("SoLuong")
                        If comboTien.SelectedValue = "VND" Then
                            dgvSanPhamHopdong_Tab1("ThanhTien", i).Value = LamTron(tempListProduct.Rows(i)("ThanhTien"), 0).ToString("N02", US)
                        ElseIf comboTien.SelectedValue = "USD" Or comboTien.SelectedValue = "SGD" Then
                            dgvSanPhamHopdong_Tab1("ThanhTien", i).Value = LamTron(tempListProduct.Rows(i)("ThanhTien"), 2).ToString("N02", US)
                        End If

                        dgvSanPhamHopdong_Tab1("LoaiPhi", i).Value = tempListProduct.Rows(i)("LoaiPhi")

                    Else
                        'Bind Lai Don Gia
                        'Dim listPrice As New List(Of String)
                        listPrice = New List(Of String)
                        Dim comboxPrice As New DataGridViewComboBoxCell
                        listPrice.Add("")
                        comboxPrice = CType(dgvSanPhamHopdong_Tab1("DonGia", i), DataGridViewComboBoxCell)
                        comboxPrice.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing
                        comboxPrice.DataSource = listPrice
                        comboxPrice.Value = ""
                        dgvSanPhamHopdong_Tab1("SoLuong", i).Value = ""
                        dgvSanPhamHopdong_Tab1("ThanhTien", i).Value = ""
                        dgvSanPhamHopdong_Tab1("LoaiPhi", i).Value = tempListProduct.Rows(i)("LoaiPhi")
                        dgvSanPhamHopdong_Tab1.Rows(i).DefaultCellStyle.BackColor = Color.White
                    End If
                Next
                'FormatPriceByCustomer()
                TinhTienHangChuaThue()
                TinhTienThueVAT()
                TinhTienThueDaThue()
            Catch ex As Exception

            End Try
        End Sub
#End Region
#Region "Xử lý sản phầm nhiều giá"
        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Kiểm tra xem sản phẩm đó có nhiều giá hay ko
        ''' </summary>
        ''' <remarks>
        ''' 
        ''' </remarks>
        ''' <history>
        '''   [lamtn] 25/03/2011  Created
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Private Function FormatPriceByCustomer() As Boolean
            Try
                'Nếu Khách Vãng Lai Thì Không Kiểm Tra
                If lblKhachHangId.Text <> "0" Or lblKhachHangId.Text <> "" Then
                    Dim dbConn As New OleDb.OleDbConnection
                    Dim dataAccess As New DataAccess
                    Dim adapter As OleDb.OleDbDataAdapter
                    Dim dbCommand As OleDb.OleDbCommand
                    Dim dtPriceByCustomer As New DataTable
                    dataAccess.ConnectDatabase_DBAccess(dbConn)
                    'connect spGetPriceByCustomer
                    dbCommand = New OleDbCommand("spGetPriceByCustomer", dbConn)
                    dbCommand.CommandType = CommandType.StoredProcedure
                    dbCommand.Parameters.Add("@KhachHangId", OleDbType.Integer).Value = lblKhachHangId.Text
                    adapter = New OleDb.OleDbDataAdapter(dbCommand)
                    adapter.Fill(dtPriceByCustomer)
                    adapter.Dispose()
                    dbConn.Close()
                    dbConn.Dispose()
                    'Khách Hàng có sản phẩm nhiều giá
                    Dim IDSanPham As String
                    If dtPriceByCustomer.Rows.Count > 0 Then
                        For i As Integer = 0 To dgvSanPhamHopdong_Tab1.RowCount - 1
                            IDSanPham = dgvSanPhamHopdong_Tab1("IDSanPham", i).Value
                            If CheckRowContains(dtPriceByCustomer, "IDSanPham", IDSanPham) And IDSanPham <> "0" Then
                                MessageBox.Show(IDSanPham)
                            End If
                        Next
                    End If
                End If

            Catch ex As Exception

            End Try
        End Function
        Private Function CheckRowContains(ByVal dtCheck As DataTable, ByVal FieldName As String, ByVal contain As String) As Boolean
            Try
                Dim bRet As Boolean = False
                For Each dr As DataRow In dtCheck.Rows
                    dr(FieldName) = contain
                    bRet = True
                    Exit For
                Next
                Return bRet
            Catch ex As Exception
                Throw
            End Try
        End Function
#End Region
#End Region
        Private Sub dgvSanPhamHopdong_Tab1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles dgvSanPhamHopdong_Tab1.KeyDown
            Try
                KeyEnterOnGridDetail = False
                'Delete Row
                If e.KeyCode = Keys.Delete Then
                    REM Delete Row
                    DeleteRow(dgvSanPhamHopdong_Tab1.CurrentCell.RowIndex)
                ElseIf e.KeyCode = Keys.Up Or e.KeyCode = Keys.Down Then

                ElseIf e.KeyCode = Keys.F1 Then
                    Panel_MucTruHoaDon.Visible = True
                    'Set Location
                    'Get Current Location
                    Dim newPoint As New Point
                    newPoint.X = 58
                    newPoint.Y = dgvSanPhamHopdong_Tab1.CurrentRow.Index * 22 + 188
                    If newPoint.Y + 183 > 580 Then
                        newPoint.Y = (newPoint.Y - 22) - 183
                    End If
                    Panel_MucTruHoaDon.Location = newPoint
                    dgvGiamTru.Focus()
                    'Kiem Tra Xem Co Gia Uu Dai Ko
                    Dim dbConn As New OleDb.OleDbConnection
                    Dim dataAccess As New DataAccess
                    Dim adapter As OleDb.OleDbDataAdapter
                    dataAccess.ConnectDatabase_DBAccess(dbConn)
                    'check xem khach hang nay co giam tru dc biet ko
                    Dim query As String = "Select Count(*) As Total From MucTruHoaDonTheoKhachHang Where xoa=0 and KhachHangId=" & IIf(lblKhachHangId.Text = "", "0", lblKhachHangId.Text)
                    Dim dtCount As New DataTable
                    adapter = New OleDb.OleDbDataAdapter(query, dbConn)
                    adapter.Fill(dtCount)
                    If dtCount.Rows(0)("Total") > 0 Then
                        GiamTruHoaDonTheoKhachHang(lblKhachHangId.Text.Trim)
                    Else
                        GiamTruHoaDon()
                    End If
                ElseIf e.KeyCode = Keys.F3 Then
                    If dgvSanPhamHopdong_Tab1.CurrentCell.ColumnIndex = 4 Then
                        'Kiem Tra Neu DonGia Hoac SoLuong Bang Trong Thi Set Ve 0.00
                        Dim IDSanPham As String = dgvSanPhamHopdong_Tab1(0, dgvSanPhamHopdong_Tab1.CurrentCell.RowIndex).Value
                        If Not (IsDBNull(IDSanPham) Or String.IsNullOrEmpty(IDSanPham) Or IDSanPham = "0") Then
                            Dim dlResult As DialogResult
                            dlResult = MessageBox.Show("Bạn muốn cập nhật giá này vào danh mục sản phẩm", "Thông báo", MessageBoxButtons.OKCancel, MessageBoxIcon.Information)
                            If dlResult = Windows.Forms.DialogResult.OK Then
                                Dim dataAccess As New DataAccess
                                Dim dbConn As New OleDb.OleDbConnection
                                Dim dbCommand As OleDbCommand
                                dataAccess.ConnectDatabase_DBAccess(dbConn)
                                Dim query As String = ""
                                Dim DonGia As Single
                                'fix
                                Dim combo As New DataGridViewComboBoxCell
                                combo = CType(dgvSanPhamHopdong_Tab1(4, dgvSanPhamHopdong_Tab1.CurrentCell.RowIndex), DataGridViewComboBoxCell)
                                'DonGia = Single.Parse(dgvSanPhamHopdong_Tab1(4, dgvSanPhamHopdong_Tab1.CurrentCell.RowIndex).Value)
                                DonGia = combo.EditedFormattedValue
                                MessageBox.Show(DonGia)
                                query = String.Format("Update SanPham Set DonGia={0} Where IDSanPham={1}", DonGia, IDSanPham)
                                dbCommand = New OleDbCommand(query, dbConn)
                                dbCommand.ExecuteNonQuery()
                                dbConn.Close()
                            End If
                        End If
                    End If
                End If
            Catch ex As Exception

            End Try
        End Sub

        Private Sub CapNhatDonHang()
            Try
                'Cap Nhat 
                dtSanPhamHD = InitOrderTable()
                'Save Temp
                Dim tempRow As DataRow
                For i As Integer = 0 To dgvSanPhamHopdong_Tab1.Rows.Count - 1
                    Dim MasanPham As Object = dgvSanPhamHopdong_Tab1(1, i).Value
                    If TypeOf (MasanPham) Is String Then
                        If String.IsNullOrEmpty(MasanPham) Then
                            Continue For
                        Else
                            If dgvSanPhamHopdong_Tab1(0, i).Value Then
                                tempRow = dtSanPhamHD.NewRow
                                tempRow.Item("RowIndex") = 0
                                tempRow.Item("IDSanPham") = dgvSanPhamHopdong_Tab1(0, i).Value
                                tempRow.Item("MaSanPham") = dgvSanPhamHopdong_Tab1(1, i).Value
                                tempRow.Item("TenSanPham") = dgvSanPhamHopdong_Tab1(1, i).Value
                                tempRow.Item("TenQuyCach") = dgvSanPhamHopdong_Tab1(3, i).Value
                                tempRow.Item("DonGia") = dgvSanPhamHopdong_Tab1(4, i).Value
                                tempRow.Item("SoLuong") = dgvSanPhamHopdong_Tab1(5, i).Value
                                tempRow.Item("ThanhTien") = dgvSanPhamHopdong_Tab1(6, i).Value
                                tempRow.Item("LoaiPhi") = dgvSanPhamHopdong_Tab1(7, i).Value
                                dtSanPhamHD.Rows.Add(tempRow)
                            End If
                        End If
                    ElseIf TypeOf (MasanPham) Is DBNull Then
                        Continue For
                    End If
                Next
            Catch ex As Exception

            End Try
        End Sub
        Private Sub dgvGiamTru_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles dgvGiamTru.KeyDown
            Try
                Select Case e.KeyCode
                    Case Keys.Down
                    Case Keys.Up
                    Case Keys.Escape
                        Panel_MucTruHoaDon.Visible = False
                        dgvSanPhamHopdong_Tab1.Focus()
                    Case Keys.Enter
                        Dim IDSanPham As String
                        Dim MaSanPham As String
                        Dim TenSanPham As String
                        Dim DonViTinh As String = ""
                        Dim DonGia As String
                        IDSanPham = dgvGiamTru.CurrentRow.Cells(0).Value
                        MaSanPham = dgvGiamTru.CurrentRow.Cells(2).Value
                        TenSanPham = "---"
                        DonGia = dgvGiamTru.CurrentRow.Cells(3).Value
                        DonViTinh = "---"
                        dgvSanPhamHopdong_Tab1.CurrentRow.Cells("IDSanPham").Value = IDSanPham
                        dgvSanPhamHopdong_Tab1.CurrentRow.Cells("LoaiPhi").Value = "GiamTru"
                        'dgvSanPhamHopdong_Tab1.CurrentRow.Cells(1).Value = dgvSanPhamHopdong_Tab1.CurrentCell.RowIndex + 1
                        dgvSanPhamHopdong_Tab1.CurrentRow.Cells("MaHang").Value = MaSanPham
                        dgvSanPhamHopdong_Tab1.CurrentRow.Cells("TenHang").Value = TenSanPham
                        dgvSanPhamHopdong_Tab1.CurrentRow.Cells("DonViTinh").Value = DonViTinh
                        Dim comboxPrice As DataGridViewComboBoxCell
                        Dim listPrice As List(Of String)
                        comboxPrice = CType(dgvSanPhamHopdong_Tab1("DonGia", dgvSanPhamHopdong_Tab1.CurrentCell.RowIndex), DataGridViewComboBoxCell)
                        listPrice = New List(Of String)
                        listPrice.Add(DonGia)
                        comboxPrice.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing
                        comboxPrice.DataSource = listPrice
                        comboxPrice.Value = DonGia
                        'dgvSanPhamHopdong_Tab1.CurrentRow.Cells("DonGia").Value = DonGia
                        dgvSanPhamHopdong_Tab1.CurrentRow.Cells("SoLuong").Value = 1
                        'Tính Thành Tiền Lun
                        'update price
                        Dim cellEdit As DataGridViewCell
                        cellEdit = dgvSanPhamHopdong_Tab1.CurrentRow.Cells("DonGia")
                        dgvSanPhamHopdong_Tab1.CurrentCell = cellEdit
                        dgvSanPhamHopdong_Tab1.BeginEdit(True)

                        Panel_MucTruHoaDon.Visible = False
                        KeyEnterOnGridDetail = True
                End Select
            Catch ex As Exception

            End Try
        End Sub


        Private Sub cmdClose_PanelGiamTru_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdClose_PanelGiamTru.Click
            Try
                Panel_MucTruHoaDon.Visible = False
                dgvSanPhamHopdong_Tab1.Focus()
            Catch ex As Exception

            End Try
        End Sub

        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Xử lý sự kiện khi đánh các phím chữ thì focus về txtTenKhachHang còn Enter thì lấy thông tin
        ''' </summary>
        ''' <remarks>
        ''' 
        ''' </remarks>
        ''' <history>
        '''   [lamtn] 18/02/2011  Created
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Private Sub dgv_KhachHang_QuickSearch_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles dgv_KhachHang_QuickSearch.KeyDown
            Try
                Select Case e.KeyCode
                    Case Keys.Down
                        Panel_KhachHang.Visible = True
                    Case Keys.Up
                        Panel_KhachHang.Visible = True
                    Case Keys.Enter
                        lblKhachHangId.Text = dgv_KhachHang_QuickSearch.Rows(dgv_KhachHang_QuickSearch.CurrentCell.RowIndex).Cells("KhachHangId_Search").Value.ToString()
                        '---------Lấy Thống Tin Khách Hàng----------
                        Dim dbConn As New OleDb.OleDbConnection
                        Dim dataAccess As New DataAccess
                        Dim dsTinhThanh As New DataSet
                        Dim dtTinhThanh As New DataTable
                        Dim query As String = "Select * From DanhMucKhachHang Where KhachHangId=" & lblKhachHangId.Text
                        Dim adapter As OleDb.OleDbDataAdapter
                        dataAccess.ConnectDatabase_DBAccess(dbConn)
                        adapter = New OleDb.OleDbDataAdapter(query, dbConn)
                        adapter.Fill(dsTinhThanh)

                        dtTinhThanh = dsTinhThanh.Tables(0)
                        '
                        txtMaKhachHang.Text = IIf(IsDBNull(dtTinhThanh.Rows(0)("CodeKhachHang")), "", dtTinhThanh.Rows(0)("CodeKhachHang"))
                        txtTenKhachHang.Text = IIf(IsDBNull(dtTinhThanh.Rows(0)("TenKhachHang")), "", dtTinhThanh.Rows(0)("TenKhachHang"))
                        txtDiaChi.Text = dtTinhThanh.Rows(0)("DiaChi")
                        txtMaSoThue.Text = IIf(IsDBNull(dtTinhThanh.Rows(0)("MaSoThue")), "", dtTinhThanh.Rows(0)("MaSoThue"))
                        cbxNhanVienTT.SelectedValue = Integer.Parse(IIf(IsDBNull(dtTinhThanh.Rows(0)("NhanVienTiepThiId")), 0, dtTinhThanh.Rows(0)("NhanVienTiepThiId").ToString))
                        '
                        Panel_KhachHang.Visible = False
                        ''txtMaSoThue.Focus()
                        ''load lại giảm trừ hóa đơn
                        ''check xem khach hang nay co giam tru dc biet ko
                        'query = "Select Count(*) As Total From muctruhoadontheokhachhang Where xoa=0 and KhachHangId=" & lblKhachHangId.Text
                        'Dim dtCount As New DataTable
                        'adapter = New OleDb.OleDbDataAdapter(query, dbConn)
                        'adapter.Fill(dtCount)
                        'If dtCount.Rows(0)("Total") > 0 Then
                        '    GiamTruHoaDonTheoKhachHang(lblKhachHangId.Text)
                        'Else
                        '    GiamTruHoaDon()
                        'End If
                        ''Load lại bảng giá sản phẩm
                        ''Kiem Tra Khach Hang Co Duoc Uu Tien Gia San Pham 
                        'query = "Select Count(*) As Total From SanPhamNhieuGia Where xoa=0 and KhachHangId=" & lblKhachHangId.Text
                        'dtCount = New DataTable
                        'adapter = New OleDb.OleDbDataAdapter(query, dbConn)
                        'adapter.Fill(dtCount)
                        'If dtCount.Rows(0)("Total") > 0 Then
                        '    SanPhamTheoKhachHang_Load("", lblKhachHangId.Text.Trim)
                        'Else
                        '    SanPham_Load("")
                        'End If
                        dbConn.Close()
                        txtHinhThucThanhToan.Focus()
                    Case Else
                        txtTenKhachHang.Focus()
                End Select
            Catch ex As Exception

            End Try
        End Sub

        Private Sub dgvGiamTru_Paint1(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles dgvGiamTru.Paint
            Try
                Dim newFont As New Font(dgvGiamTru.Font, FontStyle.Bold)
                For i As Integer = 0 To dgvGiamTru.Rows.Count - 1
                    If dgvGiamTru.Item("TypeTruHoaDon", i).Value = "1" Then
                        dgvGiamTru.Rows(i).DefaultCellStyle.BackColor = Color.YellowGreen
                        dgvGiamTru.Rows(i).DefaultCellStyle.Font = newFont
                    End If
                Next
            Catch ex As Exception

            End Try
        End Sub


        Private Sub DisableTiepThi()
            cbxNhanVienTT.Enabled = False
            txtDaiLy.Enabled = False
        End Sub

        Private Sub rbtNhanVienTiepThi_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rbtNhanVienTiepThi.CheckedChanged
            Try
                DisableTiepThi()
                cbxNhanVienTT.Enabled = True
                txtDaiLy.Text = ""
                lblDaiLyId.Text = "0"
            Catch ex As Exception

            End Try
        End Sub
        Private Sub rbtDaiLy_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rbtDaiLy.CheckedChanged
            Try
                DisableTiepThi()
                txtDaiLy.Enabled = True
            Catch ex As Exception

            End Try
        End Sub






        Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
            Try
                frmThemKhachHang.ViewDetail = True
                frmThemKhachHang.KhachHangId = lblKhachHangId.Text
                ShowModalForm(frmThemKhachHang, False, False)
                frmThemKhachHang.ViewDetail = False
            Catch ex As Exception

            End Try
        End Sub

        Private Sub Edit()
            Try
                Dim IdDonHangBan As Integer = Integer.Parse(dgvKhachHang.Rows(dgvKhachHang.CurrentCell.RowIndex).Cells("IdDonHangBan").Value.ToString)
                'check TrangThai
                'check tình trạng, nếu đơn hàng đã duyệt thì không thể xóa
                Dim dbConn As New OleDb.OleDbConnection
                Dim dataAccess As New DataAccess
                Dim query As String
                dataAccess.ConnectDatabase_DBAccess(dbConn)
                Dim TrangThai As String = ""
                Dim dbCommand As OleDb.OleDbCommand
                query = "Select TrangThai From DonHangBan Where IdDonHangBan=" & IdDonHangBan
                dbCommand = New OleDbCommand(query, dbConn)
                TrangThai = dbCommand.ExecuteScalar()
                If TrangThai = "Đã duyệt" Then
                    MessageBox.Show("Đơn hàng đã được duyệt.Bạn không thể chỉnh sửa đơn hàng này", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error)
                    dbConn.Close()
                    Exit Sub
                End If
                '
                TabControl1.SelectedTab = cmdXemThongTinChiTiet
                'show info for edit
                Dim NgayBan As String = dtpTheoNgay.Value.ToString.Split(" ")(0)
                query = "Select * From DonHangBan Where IDDonHangBan=" & IdDonHangBan
                Dim dsThongKe As New DataSet
                Dim adapter As OleDb.OleDbDataAdapter
                adapter = New OleDb.OleDbDataAdapter(query, dbConn)
                adapter.Fill(dsThongKe)

                'Thong Tin Khach Hang
                txtHoTenNguoiMua.Text = dsThongKe.Tables(0).Rows(0)("TenNguoiMua")
                txtTenKhachHang.Text = dsThongKe.Tables(0).Rows(0)("TenKhachHang")
                lblKhachHangId.Text = dsThongKe.Tables(0).Rows(0)("KhachHangId")
                txtDiaChi.Text = dsThongKe.Tables(0).Rows(0)("DiaChi")
                txtMaSoThue.Text = dsThongKe.Tables(0).Rows(0)("MaSoThue")
                dtpNgayHopDong.Value = dsThongKe.Tables(0).Rows(0)("NgayBan")
                txtMaKhachHang.Text = dsThongKe.Tables(0).Rows(0)("CodeKhachHang")
                txtHinhThucThanhToan.Text = dsThongKe.Tables(0).Rows(0)("HinhThucThanhToan")
                'Kiem Tra Tiep Thi
                If dsThongKe.Tables(0).Rows(0)("HinhThucTiepThi") = "Đại lý" Then
                    rbtDaiLy.Checked = True
                    rbtNhanVienTiepThi.Checked = False
                    txtDaiLy.Text = dsThongKe.Tables(0).Rows(0)("NhanVienTiepThi")
                    lblDaiLyId.Text = dsThongKe.Tables(0).Rows(0)("NhanVienTiepThiId")
                Else
                    rbtDaiLy.Checked = False
                    rbtNhanVienTiepThi.Checked = True
                    cbxNhanVienTT.SelectedValue = dsThongKe.Tables(0).Rows(0)("NhanVienTiepThiId")
                End If
                txtVat.Text = dsThongKe.Tables(0).Rows(0)("ThueVat")
                'Thong Tin Don Hang
                'khoi tao lai
                dtSanPhamHD = InitOrderTable()
                Dim newRow As DataRow
                Dim dsDonHang As New DataSet
                Dim dtDonHang As New DataTable
                query = "Select * From ChiTietDonHangBan Where IdDonHangBan=" & IdDonHangBan
                adapter = New OleDb.OleDbDataAdapter(query, dbConn)
                adapter.Fill(dsDonHang)
                dtDonHang = dsDonHang.Tables(0)
                For i As Integer = 0 To dtDonHang.Rows.Count - 1
                    newRow = dtSanPhamHD.NewRow
                    newRow.Item("IDSanPham") = dtDonHang.Rows(i)("IdSanPham")
                    newRow.Item("MaSanPham") = dtDonHang.Rows(i)("TenSanPham")
                    newRow.Item("TenSanPham") = dtDonHang.Rows(i)("TenSanPham")
                    newRow.Item("TenQuyCach") = dtDonHang.Rows(i)("TenQuyCach")
                    newRow.Item("SoLuong") = dtDonHang.Rows(i)("SoLuong")
                    newRow.Item("DonGia") = dtDonHang.Rows(i)("DonGia")
                    newRow.Item("ThanhTien") = dtDonHang.Rows(i)("ThanhTien")
                    newRow.Item("LoaiPhi") = dtDonHang.Rows(i)("LoaiPhi")
                    dtSanPhamHD.Rows.Add(newRow)
                Next
                'Phat Sinh Dong Trang
                Dim iRowEmpty As Integer = 15 - dtDonHang.Rows.Count - 1
                For i As Integer = 0 To iRowEmpty
                    newRow = dtSanPhamHD.NewRow
                    newRow.Item("IDSanPham") = 0
                    newRow.Item("MaSanPham") = ""
                    newRow.Item("TenSanPham") = ""
                    newRow.Item("TenQuyCach") = ""
                    newRow.Item("SoLuong") = ""
                    newRow.Item("DonGia") = ""
                    newRow.Item("ThanhTien") = ""
                    newRow.Item("LoaiPhi") = ""
                    dtSanPhamHD.Rows.Add(newRow)
                Next
                dtSanPhamHD.DefaultView.Sort = "LoaiPhi DESC"
                dgvSanPhamHopdong_Tab1.AutoGenerateColumns = False
                dgvSanPhamHopdong_Tab1.DataSource = dtSanPhamHD
                ThongTinTienHoaDon()
                'check load giam tru
                query = "Select Count(*) As Total From muctruhoadontheokhachhang Where xoa=0 and KhachHangId=" & lblKhachHangId.Text
                Dim dtCount As New DataTable
                adapter = New OleDb.OleDbDataAdapter(query, dbConn)
                adapter.Fill(dtCount)
                If dtCount.Rows(0)("Total") > 0 Then
                    GiamTruHoaDonTheoKhachHang(lblKhachHangId.Text)
                Else
                    GiamTruHoaDon()
                End If
                dbConn.Close()
                ChinhSuaKhoanGiamTru(dtSanPhamHD)
                IdDonHangBan_Edit = IdDonHangBan
            Catch ex As Exception
                MessageBox.Show(ex.ToString)
            End Try
        End Sub
        Private Sub Print()
            Dim IdDonHangBan As Integer = Integer.Parse(dgvKhachHang.Rows(dgvKhachHang.CurrentCell.RowIndex).Cells("IdDonHangBan").Value.ToString)
            frmInHoaDon.IdDonHangBan = IdDonHangBan
            frmInHoaDon.Show()
        End Sub
        Private Sub Duyet()
            Try
                Dim IDDonHangBan As Integer = Integer.Parse(dgvKhachHang.Rows(dgvKhachHang.CurrentCell.RowIndex).Cells("IDDonHangBan").Value.ToString)
                'check tình trạng, nếu đơn hàng đã duyệt thì không thể xóa

                Dim dbConn As New OleDb.OleDbConnection
                Dim dataAccess As New DataAccess
                Dim query As String
                dataAccess.ConnectDatabase_DBAccess(dbConn)
                Dim TrangThai As String = ""
                Dim dbCommand As OleDb.OleDbCommand
                query = "Select TrangThai From DonHangBan Where IdDonHangBan=" & IDDonHangBan
                dbCommand = New OleDbCommand(query, dbConn)
                TrangThai = dbCommand.ExecuteScalar()
                If TrangThai = "Đã duyệt" Then
                    MessageBox.Show("Đơn hàng đã được duyệt.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Hand)
                    dbConn.Close()
                    Exit Sub
                End If
                Dim dlgRes As DialogResult
                dlgRes = MessageBox.Show( _
                          "Bạn đồng ý duyệt đơn hàng này?", _
                          "Thông báo", _
                    MessageBoxButtons.OKCancel, _
                          MessageBoxIcon.Question)
                If dlgRes = Windows.Forms.DialogResult.OK Then
                    query = String.Format("Update DonHangBan Set TrangThai=N'Đã duyệt' Where IDDonHangBan={0};Update ChiTietDonHangBan Set TrangThai=N'Đã duyệt' Where IDDonHangBan={0}", IDDonHangBan)
                    dbCommand = New OleDb.OleDbCommand(query, dbConn)
                    dbCommand.ExecuteNonQuery()
                    '----------Cập nhật số lượng tồn kho----------------
                    query = "Select IdSanPham,SoLuong From ChiTietDonHangBan Where LoaiPhi='HangHoa' And IDDonHangBan=" & IDDonHangBan
                    Dim dtSoLuongSP As New DataTable
                    Dim adapter As OleDb.OleDbDataAdapter
                    adapter = New OleDb.OleDbDataAdapter(query, dbConn)
                    adapter.Fill(dtSoLuongSP)
                    Dim SoLuongTru As Single
                    For i As Integer = 0 To dtSoLuongSP.Rows.Count - 1
                        SoLuongTru = Single.Parse(dtSoLuongSP.Rows(i)("SoLuong"))
                        query = "Update SanPham Set SoLuongTon = SoLuongTon - " & SoLuongTru & " Where IdSanPham=" & dtSoLuongSP.Rows(i)("IDSanPham")
                        dbCommand = New OleDbCommand(query, dbConn)
                        dbCommand.ExecuteNonQuery()
                    Next
                    dbConn.Close()
                    '
                    Select Case ReportType
                        Case 0
                            Report_TheoNgay()
                        Case 1
                            Report_TheoThang()
                        Case 2
                            Report_TheoNam()
                        Case 3
                            Report_TuNgayDenNgay()
                        Case Else
                            Report_TenKhachHang()
                    End Select
                End If
            Catch ex As Exception

            End Try
        End Sub
        Private Sub Huy()
            Try
                Dim IDDonHangBan As Integer = Integer.Parse(dgvKhachHang.Rows(dgvKhachHang.CurrentCell.RowIndex).Cells("IDDonHangBan").Value.ToString)
                'check tình trạng, nếu đơn hàng đã duyệt thì không thể xóa

                Dim dbConn As New OleDb.OleDbConnection
                Dim dataAccess As New DataAccess
                Dim query As String
                dataAccess.ConnectDatabase_DBAccess(dbConn)
                Dim TrangThai As String = ""
                Dim dbCommand As OleDb.OleDbCommand
                query = "Select TrangThai From DonHangBan Where IdDonHangBan=" & IDDonHangBan
                dbCommand = New OleDbCommand(query, dbConn)
                TrangThai = dbCommand.ExecuteScalar()
                If TrangThai = "Đã hủy" Then
                    MessageBox.Show("Đơn hàng đã được hủy.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Hand)
                    dbConn.Close()
                    Exit Sub
                End If
                Dim dlgRes As DialogResult
                dlgRes = MessageBox.Show( _
                          "Bạn đồng ý hủy đơn hàng này?", _
                          "Thông báo", _
                    MessageBoxButtons.OKCancel, _
                          MessageBoxIcon.Question)
                If dlgRes = Windows.Forms.DialogResult.OK Then
                    query = String.Format("Update DonHangBan Set TrangThai=N'Đã hủy' Where IDDonHangBan={0};Update ChiTietDonHangBan Set TrangThai=N'Đã hủy' Where IDDonHangBan={0}", IDDonHangBan)
                    dbCommand = New OleDb.OleDbCommand(query, dbConn)
                    dbCommand.ExecuteNonQuery()
                    dbConn.Close()
                    '
                    Select Case ReportType
                        Case 0
                            Report_TheoNgay()
                        Case 1
                            Report_TheoThang()
                        Case 2
                            Report_TheoNam()
                        Case 3
                            Report_TuNgayDenNgay()
                        Case 4
                            Report_TenKhachHang()
                        Case 5
                            Report_SoHoaDon()
                    End Select
                End If
            Catch ex As Exception

            End Try
        End Sub
        Private Sub XoaDonHang()
            Try
                Dim IDDonHangBan As Integer = Integer.Parse(dgvKhachHang.Rows(dgvKhachHang.CurrentCell.RowIndex).Cells("IDDonHangBan").Value.ToString)
                'check tình trạng, nếu đơn hàng đã duyệt thì không thể xóa
                Dim dbConn As New OleDb.OleDbConnection
                Dim dataAccess As New DataAccess
                Dim query As String
                dataAccess.ConnectDatabase_DBAccess(dbConn)
                Dim TrangThai As String = ""
                Dim dbCommand As OleDb.OleDbCommand
                query = "Select TrangThai From DonHangBan Where IdDonHangBan=" & IDDonHangBan
                dbCommand = New OleDbCommand(query, dbConn)
                TrangThai = dbCommand.ExecuteScalar()
                Dim dlgRes As DialogResult
                If TrangThai = "Đã duyệt" Then
                    dlgRes = MessageBox.Show("Đơn hàng đã được duyệt.Bạn đồng ý xóa đơn hàng này.Vui lòng kiểm tra thông tin trước khi thực hiện", "Thông báo", MessageBoxButtons.OKCancel, MessageBoxIcon.Error)
                    If dlgRes = Windows.Forms.DialogResult.Cancel Then
                        dbConn.Close()
                        Exit Sub
                    End If
                End If
                dlgRes = MessageBox.Show( _
                          "Bạn muốn xóa thông tin đơn hàng này", _
                          "Thông báo", _
                    MessageBoxButtons.OKCancel, _
                          MessageBoxIcon.Question)
                If dlgRes = Windows.Forms.DialogResult.OK Then
                    query = String.Format("Delete From DonHangBan Where IDDonHangBan={0};Delete From ChiTietDonHangBan Where IDDonHangBan={0}", IDDonHangBan)
                    dbCommand = New OleDb.OleDbCommand(query, dbConn)
                    dbCommand.ExecuteNonQuery()
                    dbConn.Close()
                    Select Case ReportType
                        Case 0
                            Report_TheoNgay()
                        Case 1
                            Report_TheoThang()
                        Case 2
                            Report_TheoNam()
                        Case 3
                            Report_TuNgayDenNgay()
                        Case Else
                            Report_TenKhachHang()
                    End Select
                End If
            Catch ex As Exception

            End Try
        End Sub




        Private Sub txtVat_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtVat.Leave
            Try
                If txtVat.Text = "" Then
                    txtVat.Text = "10.00"
                End If
                TinhTienThueVAT()
                TinhTienThueDaThue()
            Catch ex As Exception
                MessageBox.Show(ex.ToString, "Thông báo", MessageBoxButtons.OK)
            End Try
        End Sub

#Region "Đơn hàng"
        '
#End Region
        Private Sub txtTenKhachHang_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtTenKhachHang.Leave
            Try
                Panel_KhachHang.Visible = False
            Catch ex As Exception

            End Try
        End Sub

        Private Sub Esc_HotKey_Pressed(ByVal sender As System.Object, ByVal e As System.EventArgs)
            Try
                Me.Close()
            Catch ex As Exception

            End Try
        End Sub

        Private Sub dgvSanPhamHopdong_Tab1_CellLeave(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvSanPhamHopdong_Tab1.CellLeave
            Try
                'If e.ColumnIndex = 5 Or e.ColumnIndex = 6 Then
                '    Dim IDSanPham As Integer = Integer.Parse(dgvSanPhamHopdong_Tab1(0, e.RowIndex).Value)
                '    If IDSanPham > 0 Then
                '       FormatNumberCell(dgvSanPhamHopdong_Tab1.CurrentCell)
                '    End If
                'End If
            Catch ex As Exception

            End Try
        End Sub

        'Private Sub dgvSanPhamHopdong_Tab1_CellEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvSanPhamHopdong_Tab1.CellEnter
        '    Try
        '        'If dgvSanPhamHopdong_Tab1.CurrentCell.ColumnIndex = 1 Then
        '        '    Dim nextindex As Integer = Math.Min(dgvSanPhamHopdong_Tab1.Columns.Count - 1, dgvSanPhamHopdong_Tab1.CurrentCell.ColumnIndex + 1)
        '        '    Dim method As New SetColumnIndex(AddressOf Mymethod)
        '        '    dgvSanPhamHopdong_Tab1.BeginInvoke(method, nextindex)
        '        'End If
        '    Catch ex As Exception

        '    End Try
        'End Sub
        'Delegate Sub SetColumnIndex(ByVal i As Integer)
        'Private Sub Mymethod(ByVal columnIndex As Integer)

        '    dgvSanPhamHopdong_Tab1.CurrentCell = dgvSanPhamHopdong_Tab1.CurrentRow.Cells(columnIndex)

        '    'dgvSanPhamHopdong_Tab1.BeginEdit(True)

        'End Sub
        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' generate order number for order form
        ''' </summary>
        ''' <remarks>
        ''' 
        ''' </remarks>
        ''' <history>
        '''   [lamtn] 05/03/2011  Created
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Private Sub GenerateOrderNumber()
            Try
                Dim dtNoOrder As New DataTable
                Dim NoOrder As DataRow
                dtNoOrder.Columns.Add("STT")
                For i As Integer = 0 To 11
                    NoOrder = dtNoOrder.NewRow
                    NoOrder.Item("STT") = i + 1
                    dtNoOrder.Rows.Add(NoOrder)
                    dtNoOrder.AcceptChanges()
                Next
                dgvNoOrder.DataSource = dtNoOrder
                dgvNoOrder.ClearSelection()
            Catch ex As Exception

            End Try
        End Sub


        Private Sub cmdIn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdIn.Click
            Try
                Order_Save()
                If cbxTruKho.Checked Then
                    Order_TruKho()
                End If
                Order_Print()
                Order_Clear()
            Catch ex As Exception

            End Try
        End Sub

        Private Sub dgvKhachHang_Search_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles dgvKhachHang_Search.KeyDown
            If e.KeyCode = Keys.Enter Then
                txtTenKhachHang_Search.Text = dgvKhachHang_Search.Rows(dgvKhachHang_Search.CurrentCell.RowIndex).Cells("TenKhachHang_S").Value.ToString()
                Panel_KhachHang_Search.Visible = False
                cmdThongKe.Focus()
            ElseIf e.KeyCode = Keys.Down Or Keys.Up Then

            End If
        End Sub







        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Preview Order
        ''' </summary>
        ''' <remarks>
        ''' 
        ''' </remarks>
        ''' <history>
        '''   [lamtn] 05/03/2011  Created
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Private Sub cmdXem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdXem.Click
            Try
                Order_PrintPreview()
            Catch ex As Exception

            End Try
        End Sub
        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Customer Info Table
        ''' </summary>
        ''' <remarks>
        ''' 
        ''' </remarks>
        ''' <history>
        '''   [lamtn] 05/03/2011  Created
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Protected Function InitCustomerTable() As DataTable
            Dim dtTable As DataTable = New DataTable()
            Try

                Dim TenKhachHang As DataColumn = New DataColumn("TenKhachHang")
                TenKhachHang.DataType = System.Type.GetType("System.String")
                dtTable.Columns.Add(TenKhachHang)

                Dim DiaChi As DataColumn = New DataColumn("DiaChi")
                DiaChi.DataType = System.Type.GetType("System.String")
                dtTable.Columns.Add(DiaChi)

                Dim MaSoThue As DataColumn = New DataColumn("MaSoThue")
                MaSoThue.DataType = System.Type.GetType("System.String")
                dtTable.Columns.Add(MaSoThue)

                Dim TenQuyCach As DataColumn = New DataColumn("TenQuyCach")
                TenQuyCach.DataType = System.Type.GetType("System.String")
                dtTable.Columns.Add(TenQuyCach)

                Dim HinhThucThanhToan As DataColumn = New DataColumn("HinhThucThanhToan")
                HinhThucThanhToan.DataType = System.Type.GetType("System.String")
                dtTable.Columns.Add(HinhThucThanhToan)

                Dim NhanVienTiepThi As DataColumn = New DataColumn("NhanVienTiepThi")
                NhanVienTiepThi.DataType = System.Type.GetType("System.String")
                dtTable.Columns.Add(NhanVienTiepThi)

                Return dtTable
            Catch ex As Exception
                Throw
            End Try
        End Function
        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Order Value
        ''' </summary>
        ''' <remarks>
        ''' 
        ''' </remarks>
        ''' <history>
        '''   [lamtn] 05/03/2011  Created
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Protected Function ThongTinTienDonHang() As DataTable
            Dim dtTable As DataTable = New DataTable()
            Try

                Dim TienHang As DataColumn = New DataColumn("TienHang")
                TienHang.DataType = System.Type.GetType("System.String")
                dtTable.Columns.Add(TienHang)

                Dim ThueSuatGTGT As DataColumn = New DataColumn("ThueSuatGTGT")
                ThueSuatGTGT.DataType = System.Type.GetType("System.String")
                dtTable.Columns.Add(ThueSuatGTGT)

                Dim ThueGTGT As DataColumn = New DataColumn("ThueGTGT")
                ThueGTGT.DataType = System.Type.GetType("System.String")
                dtTable.Columns.Add(ThueGTGT)

                Dim TongThanhToan As DataColumn = New DataColumn("TongThanhToan")
                TongThanhToan.DataType = System.Type.GetType("System.String")
                dtTable.Columns.Add(TongThanhToan)

                Dim TienBangChu As DataColumn = New DataColumn("TienBangChu")
                TienBangChu.DataType = System.Type.GetType("System.String")
                dtTable.Columns.Add(TienBangChu)
                Return dtTable
            Catch ex As Exception
                Throw
            End Try
        End Function




#Region "HotKey Events"
        Protected Overrides Function ProcessCmdKey(ByRef msg As Message, ByVal keyData As Keys) As Boolean
            ' if it is a hotkey, return true; otherwise, return false
            Select Case keyData
                Case Keys.Control Or Keys.Tab
                    'Change TAB
                    ChangeTab()
                    Return True
                Case Keys.Control Or Keys.S
                    'Lưu hóa đơn
                    If TabControl1.SelectedTab.Name = "cmdXemThongTinChiTiet" Then
                        Order_Save()
                        If cbxTruKho.Checked Then
                            Order_TruKho()
                        End If
                        Order_Clear()
                    End If
                    Return True
                Case Keys.Control Or Keys.P
                    'In hóa đơn
                    If TabControl1.SelectedTab.Name = "cmdXemThongTinChiTiet" Then
                        Order_Save()
                        If cbxTruKho.Checked Then
                            Order_TruKho()
                        End If
                        Order_Print()
                        Order_Clear()
                    Else
                        Order_Print2()
                    End If
                    Return True
                Case Keys.Control Or Keys.X
                    If TabControl1.SelectedTab.Name = "cmdXemThongTinChiTiet" Then
                        Order_PrintPreview()
                    End If
                    Return True
                Case Keys.Control Or Keys.H
                    If TabControl1.SelectedTab.Name = "cmdXemThongTinChiTiet" Then
                        IsViewHistory = False
                        Order_Clear()
                    End If
                    Return True
                Case Keys.Control Or Keys.E
                    If Not TabControl1.SelectedTab.Name = "cmdXemThongTinChiTiet" Then
                        IsViewHistory = False
                        Order_Edit()
                    End If
                    Return True
                Case Keys.Control Or Keys.Delete
                    If Not TabControl1.SelectedTab.Name = "cmdXemThongTinChiTiet" Then
                        Order_Delete()
                    End If
                    Return True
                Case Keys.Control Or Keys.D
                    If Not TabControl1.SelectedTab.Name = "cmdXemThongTinChiTiet" Then
                        'Order_Approved()
                    End If
                    Return True
                Case Keys.Control Or Keys.M
                    If Not TabControl1.SelectedTab.Name = "cmdXemThongTinChiTiet" Then
                        Order_Cancel()
                    End If
                    Return True
                Case Keys.Control Or Keys.K
                    If TabControl1.SelectedTab.Name = "cmdXemThongTinChiTiet" Then
                        ViewCustomerInfo()
                    End If
                    Return True
                Case Keys.Control Or Keys.Escape
                    CloseForm()
                Case Else
                    Exit Function
            End Select
            Return MyBase.ProcessCmdKey(msg, keyData)
        End Function
#End Region
#Region "Function HotKey"
        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Thay đổi TAB
        ''' </summary>
        ''' <remarks>
        ''' 
        ''' </remarks>
        ''' <history>
        '''   [lamtn] 10/03/2011  Created
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Private Sub ChangeTab()
            Try
                'TabControl1.SelectedTab = cmdXemThongTinChiTiet
                If TabControl1.SelectedTab.Name = "cmdXemThongTinChiTiet" Then
                    TabControl1.SelectedTab = TabPage2
                Else
                    TabControl1.SelectedTab = cmdXemThongTinChiTiet
                End If
            Catch ex As Exception

            End Try
        End Sub
        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Đóng Form
        ''' </summary>
        ''' <remarks>
        ''' 
        ''' </remarks>
        ''' <history>
        '''   [lamtn] 10/03/2011  Created
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Private Function CloseForm()
            Try
                Dim dlgRes As DialogResult
                dlgRes = MessageBox.Show("Bạn muốn tắt màn hình Quản lý bán hàng", "Thông báo", MessageBoxButtons.OKCancel, MessageBoxIcon.Error)
                If dlgRes = Windows.Forms.DialogResult.OK Then
                    Me.Close()
                End If
                Return True
            Catch ex As Exception
                Throw
            End Try
        End Function
        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Hàm Xem Thông Tin Khách Hàng
        ''' </summary>
        ''' <remarks>
        ''' 
        ''' </remarks>
        ''' <history>
        '''   [lamtn] 10/03/2011  Created
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Private Sub ViewCustomerInfo()
            Try
                frmThemKhachHang.ViewDetail = True
                frmThemKhachHang.KhachHangId = lblKhachHangId.Text
                ShowModalForm(frmThemKhachHang, False, False)
                frmThemKhachHang.ViewDetail = False
            Catch ex As Exception

            End Try
        End Sub
        '' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Hàm Lưu Đơn Hàng Xuống Database
        ''' </summary>
        ''' <remarks>
        ''' 
        ''' </remarks>
        ''' <history>
        '''   [lamtn] 18/02/2011  Created
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Private Sub Order_TruKho()
            Try
                Dim dbConn As New OleDb.OleDbConnection
                Dim dataAccess As New DataAccess
                Dim dbCommand As New OleDbCommand
                Dim query As String
                Dim IDDonHangBan As Integer = 0
                dataAccess.ConnectDatabase_DBAccess(dbConn)
                '---------Lay DonHangBan moi nhat
                query = "Select Max(IDDonHangBan) From DonHangBan"
                dbCommand = New OleDbCommand(query, dbConn)
                IDDonHangBan = dbCommand.ExecuteScalar()
                '----------Cap Nhat Trang Thai DonHangBan,ChiTietDonHangBan
                query = String.Format("Update DonHangBan Set TrangThai=N'Đã duyệt' Where IDDonHangBan={0};Update ChiTietDonHangBan Set TrangThai=N'Đã duyệt' Where IDDonHangBan={0}", IDDonHangBan)
                dbCommand = New OleDb.OleDbCommand(query, dbConn)
                dbCommand.ExecuteNonQuery()
                '----------Cập nhật số lượng tồn kho----------------
                'If DaTruKho = False Then
                query = "Select IdSanPham,SoLuong From ChiTietDonHangBan Where LoaiPhi='HangHoa' And IDDonHangBan=" & IDDonHangBan
                Dim dtSoLuongSP As New DataTable
                Dim adapter As OleDb.OleDbDataAdapter
                adapter = New OleDb.OleDbDataAdapter(query, dbConn)
                adapter.Fill(dtSoLuongSP)
                Dim SoLuongTru As Single
                For i As Integer = 0 To dtSoLuongSP.Rows.Count - 1
                    SoLuongTru = Single.Parse(dtSoLuongSP.Rows(i)("SoLuong"))
                    query = "Update SanPham Set SoLuongTon = SoLuongTon - " & SoLuongTru & " Where IdSanPham=" & dtSoLuongSP.Rows(i)("IDSanPham")
                    dbCommand = New OleDbCommand(query, dbConn)
                    dbCommand.ExecuteNonQuery()
                Next
                'End If
                dbConn.Close()
            Catch ex As Exception
                MessageBox.Show(ex.ToString())
            End Try
        End Sub
        '' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Hàm Lưu Đơn Hàng Xuống Database
        ''' </summary>
        ''' <remarks>
        ''' 
        ''' </remarks>
        ''' <history>
        '''   [lamtn] 18/02/2011  Created
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Private Sub Order_Save()
            Try
                '--------Luu Thong Tin Khach Hang--------------
                Dim dataAccess As New DataAccess
                Dim dbConn As New OleDb.OleDbConnection
                Dim dbCommand As OleDbCommand
                Dim query As String = ""
                dataAccess.ConnectDatabase_DBAccess(dbConn)
                Dim REFFCODE As Integer = 0
                If IdDonHangBan_Edit > 0 Then
                    'xóa 
                    REFFCODE = IdDonHangBan_Edit
                    If EditMode = 1 Then
                        query = "Update DonHangBan Set REFFCODE=" & REFFCODE & ",NgaySua='" & NgayTao() & "',NguoiSua='" & NguoiTao() & "' Where IDDonHangBan=" & IdDonHangBan_Edit & ";Update ChiTietDonHangBan Set REFFCODE=" & REFFCODE & ",NgaySua='" & NgayTao() & "',NguoiSua='" & NguoiTao() & "' Where IDDonHangBan=" & IdDonHangBan_Edit
                        dbCommand = New OleDbCommand(query, dbConn)
                        dbCommand.ExecuteNonQuery()
                    ElseIf EditMode = 2 Then
                        query = "Update DonHangBan Set REFFCODE=" & REFFCODE & ",NgayKeThua='" & NgayTao() & "',NguoiKeThua='" & NguoiTao() & "' Where IDDonHangBan=" & IdDonHangBan_Edit & ";Update ChiTietDonHangBan Set REFFCODE=" & REFFCODE & ",NgayKeThua='" & NgayTao() & "',NguoiKeThua='" & NguoiTao() & "' Where IDDonHangBan=" & IdDonHangBan_Edit
                        dbCommand = New OleDbCommand(query, dbConn)
                        dbCommand.ExecuteNonQuery()
                    End If
                    IdDonHangBan_Edit = 0
                End If
                Dim Ngay As String = dtpNgayHopDong.Value.ToString.Split(" ")(0)
                Dim Thang As Integer = Integer.Parse(Ngay.Split("/")(0))
                Dim Nam As Integer = Ngay.Split("/")(2)
                'If lblKhachHangId.Text = "" Then
                '    lblKhachHangId.Text = "0"
                'End If
                'KhachHangID 
                dbCommand = New OleDbCommand("spKhachHangID", dbConn)
                dbCommand.CommandType = CommandType.StoredProcedure
                dbCommand.Parameters.Add("@TenKhachHang", OleDbType.VarWChar).Value = txtTenKhachHang.Text
                dbCommand.Parameters.Add("@CodeKhachHang", OleDbType.VarWChar).Value = txtMaKhachHang.Text
                lblKhachHangId.Text = dbCommand.ExecuteScalar()
                'Kiểm tra hình thức tiếp thị
                Dim HinhThucTiepThi As String
                Dim NhanVienTiepThiId As String
                Dim TenNhanVienTiepThi As String
                If rbtNhanVienTiepThi.Checked Then
                    'Nhan Vien Tiep Thi
                    HinhThucTiepThi = "Nhân viên tiếp thị"
                    NhanVienTiepThiId = cbxNhanVienTT.SelectedValue
                    TenNhanVienTiepThi = cbxNhanVienTT.Text
                ElseIf rbtDaiLy.Checked Then
                    HinhThucTiepThi = "Đại lý"
                    NhanVienTiepThiId = lblDaiLyId.Text
                    TenNhanVienTiepThi = txtDaiLy.Text
                End If
                Dim TruKho As Integer = IIf(cbxTruKho.Checked, 1, 0)
                'fix tinh doanh thu
                Dim TinhDoanhThu As Integer = Integer.Parse(cbxTinhDoanhThu.CheckValue)
                'Tien
                query = "Insert Into DonHangBan(KhachHangId,CodeKhachHang,TenKhachHang,DiaChi,MaSoThue,HinhThucThanhToan,NhanVienTiepThi,NhanVienTiepThiId,ThueVAT,NgayBan,Thang,Nam,Ngay_So,TrangThai,So,HinhThucTiepThi,TenNguoiMua,PhiVanChuyen,HoaDonTang,Tien,NgayTao,NguoiTao,REFFCODE,GhiChu,TruKho,TinhDoanhThu) Values(N'" & lblKhachHangId.Text & "',N'" & txtMaKhachHang.Text & "',N'" & txtTenKhachHang.Text & "',N'" & txtDiaChi.Text & "',N'" & txtMaSoThue.Text & "',N'" & txtHinhThucThanhToan.Text & "',N'" & TenNhanVienTiepThi & "'," & NhanVienTiepThiId & ",N'" & txtVat.Text & "',N'" & Ngay & " ',N'" & Thang & "',N'" & Nam & "','" & ConvertDateToInt(Ngay) & "',N'Chưa duyệt'," & "N'" & txtSo.Text.Trim & "',N'" & HinhThucTiepThi & "',N'" & txtHoTenNguoiMua.Text.Trim & "'," & txtPhiVanChuyen.Value & "," & IIf(cbxNoPrintMoney.Checked, 1, 0) & ",N'" & comboTien.SelectedValue & "','" & NgayTao() & "','" & NguoiTao() & "'," & REFFCODE & ",N'" & txtGhiChu.Text & "'," & TruKho & "," & TinhDoanhThu & ")"
                dbCommand = New OleDbCommand(query, dbConn)
                dbCommand.ExecuteNonQuery()
                ''----------Luu Thong Tin Chi Tiet Don Hang------------
                Dim IDDonHangBan As Integer = 0
                query = "Select Max(IDDonHangBan) From DonHangBan"
                dbCommand = New OleDbCommand(query, dbConn)
                IDDonHangBan = dbCommand.ExecuteScalar()
                dtSanPhamHD = InitOrderTable()
                'Save Temp
                Dim tempRow As DataRow
                Dim IDSanPham As Object
                Dim comboPrice As New DataGridViewComboBoxCell
                For i As Integer = 0 To dgvSanPhamHopdong_Tab1.Rows.Count - 1
                    IDSanPham = dgvSanPhamHopdong_Tab1(0, i).Value
                    If TypeOf (IDSanPham) Is String Then
                        If String.IsNullOrEmpty(IDSanPham) Then
                            Continue For
                        Else
                            'If dgvSanPhamHopdong_Tab1(0, i).Value Then
                            tempRow = dtSanPhamHD.NewRow
                            tempRow.Item("RowIndex") = 0
                            tempRow.Item("IDSanPham") = dgvSanPhamHopdong_Tab1(0, i).Value
                            tempRow.Item("MaSanPham") = dgvSanPhamHopdong_Tab1(1, i).Value
                            tempRow.Item("TenSanPham") = dgvSanPhamHopdong_Tab1(1, i).Value
                            tempRow.Item("TenQuyCach") = dgvSanPhamHopdong_Tab1(3, i).Value
                            comboPrice = CType(dgvSanPhamHopdong_Tab1(4, i), DataGridViewComboBoxCell)
                            tempRow.Item("DonGia") = comboPrice.Value
                            tempRow.Item("SoLuong") = IIf(dgvSanPhamHopdong_Tab1(5, i).Value = "", 0, dgvSanPhamHopdong_Tab1(5, i).Value)
                            tempRow.Item("ThanhTien") = IIf(dgvSanPhamHopdong_Tab1(6, i).Value = "", 0, dgvSanPhamHopdong_Tab1(6, i).Value)
                            tempRow.Item("LoaiPhi") = dgvSanPhamHopdong_Tab1(7, i).Value
                            tempRow.Item("IsManyPrice") = dgvSanPhamHopdong_Tab1(8, i).Value
                            dtSanPhamHD.Rows.Add(tempRow)
                            'End If
                        End If
                    ElseIf TypeOf (IDSanPham) Is DBNull Then
                        Continue For
                    ElseIf TypeOf (IDSanPham) Is Integer Then
                        If IDSanPham > 0 Then
                            tempRow = dtSanPhamHD.NewRow
                            tempRow.Item("IDSanPham") = dgvSanPhamHopdong_Tab1("IDSanPham", i).Value
                            tempRow.Item("MaSanPham") = dgvSanPhamHopdong_Tab1("MaHang", i).Value
                            tempRow.Item("TenSanPham") = dgvSanPhamHopdong_Tab1("TenHang", i).Value
                            tempRow.Item("TenQuyCach") = dgvSanPhamHopdong_Tab1("DonViTinh", i).Value
                            comboPrice = CType(dgvSanPhamHopdong_Tab1(4, i), DataGridViewComboBoxCell)
                            tempRow.Item("DonGia") = comboPrice.Value
                            tempRow.Item("SoLuong") = IIf(dgvSanPhamHopdong_Tab1(5, i).Value = "", 0, dgvSanPhamHopdong_Tab1(5, i).Value)
                            tempRow.Item("ThanhTien") = IIf(dgvSanPhamHopdong_Tab1(6, i).Value = "", 0, dgvSanPhamHopdong_Tab1(6, i).Value)
                            tempRow.Item("LoaiPhi") = dgvSanPhamHopdong_Tab1("LoaiPhi", i).Value
                            tempRow.Item("IsManyPrice") = dgvSanPhamHopdong_Tab1(8, i).Value
                            dtSanPhamHD.Rows.Add(tempRow)
                        End If
                    End If
                Next
                For i As Integer = 0 To dtSanPhamHD.Rows.Count - 1 '--------------------------------------------------------------------------------------------------------------IDDonHangBan,KhachHangId,MaKhachHang,IDSanPham,TenSanPham,SoLuong,DonGia,ThanhTien,LoaiPhi,Ngay,Thang,Nam,NgaySo,TrangThai
                    query = String.Format("Insert Into ChiTietDonHangBan(IDDonHangBan,KhachHangId,MaKhachHang,IDSanPham,TenSanPham,SoLuong,DonGia,ThanhTien,LoaiPhi,Ngay,Thang,Nam,Ngay_So,TrangThai,TenQuyCach,MaSanPham,IsManyPrice,NgayTao,NguoiTao,REFFCODE,TruKho,TinhDoanhThu) Values({0},{1},N'{2}',{3},N'{4}',{5},{6},{7},N'{8}',N'{9}',N'{10}',N'{11}',{12},N'{13}',N'{14}',N'{15}',{16},'{17}','{18}',{19},{20},{21})", IDDonHangBan, lblKhachHangId.Text, txtMaKhachHang.Text, dtSanPhamHD.Rows(i)("IDSanPham"), dtSanPhamHD.Rows(i)("TenSanPham"), dtSanPhamHD.Rows(i)("SoLuong"), Single.Parse(dtSanPhamHD.Rows(i)("DonGia")), Single.Parse(dtSanPhamHD.Rows(i)("ThanhTien")), dtSanPhamHD.Rows(i)("LoaiPhi"), Ngay, Thang, Nam, ConvertDateToInt(Ngay), "Chưa duyệt", dtSanPhamHD.Rows(i)("TenQuyCach"), dtSanPhamHD.Rows(i)("MaSanPham"), IIf(dtSanPhamHD.Rows(i)("IsManyPrice") = "", 0, dtSanPhamHD.Rows(i)("IsManyPrice")), NgayTao, NguoiTao, REFFCODE, TruKho,TinhDoanhThu)
                    dbCommand = New OleDbCommand(query, dbConn)
                    dbCommand.ExecuteNonQuery()
                Next
                dbConn.Close()

            Catch ex As Exception
                ShowError(ex)
            End Try
        End Sub
        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Hàm In Đơn Hàng
        ''' </summary>
        ''' <remarks>
        ''' 
        ''' </remarks>
        ''' <history>
        '''   [lamtn] 18/02/2011  Created
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Private Sub Order_Print()
            Try
                Dim objReport_KhongTien As New rptHoaDon_KhongTien
                Dim objReport As New rptHoaDon
                'Lấy được chi tiết đơn hàng bán
                Dim dbConn As New OleDb.OleDbConnection
                Dim dataAccess As New DataAccess
                Dim dtChiTietDonHangBan As New DataTable
                Dim query As String
                Dim adapter As OleDb.OleDbDataAdapter
                Dim dbCommand As OleDb.OleDbCommand
                dataAccess.ConnectDatabase_DBAccess(dbConn)
                Dim IDDonHangBan As Integer = 0
                query = "Select Max(IDDonHangBan) From DonHangBan"
                dbCommand = New OleDbCommand(query, dbConn)
                IDDonHangBan = dbCommand.ExecuteScalar()
                query = "Select MaSanPham,TenSanPham,TenQuyCach,SoLuong,DonGia AS DonGiaDec,Cast(ThanhTien As VarChar(50)) As ThanhTien,LoaiPhi From ChiTietDonHangBan Where IdDonHangBan=" & IDDonHangBan & " Order By LoaiPhi DESC"
                adapter = New OleDb.OleDbDataAdapter(query, dbConn)
                adapter.Fill(dtChiTietDonHangBan)
                dtChiTietDonHangBan.Columns.Add("DonGia")

                'Upgrade To Increase Perform
                'Tính Tổng tiền hàng
                Dim TongTienHangHoa As Double = 0
                Dim TongTienGiamTru As Double = 0
                Dim TongTienHang As Double = 0
                Dim ThueSuatVAT As Double = 0
                Dim ThueVAT As Double = 0
                TongTienHangHoa = TinhTongTienHangHoa(dtChiTietDonHangBan)
                TongTienGiamTru = TinhTongTienGiamTru(dtChiTietDonHangBan)
                query = "Select ThueVAT From DonHangBan Where IdDonHangBan=" & IDDonHangBan
                dbCommand = New OleDbCommand(query, dbConn)
                ThueSuatVAT = dbCommand.ExecuteScalar()
                TongTienHang = TongTienHangHoa - TongTienGiamTru
                If comboTien.SelectedValue = "VND" Then
                    ThueVAT = LamTron((ThueSuatVAT * TongTienHang) / 100, 0)
                ElseIf comboTien.SelectedValue = "USD" Or comboTien.SelectedValue = "SGD" Then
                    ThueVAT = LamTron((ThueSuatVAT * TongTienHang) / 100, 3)
                End If

                '----Cat chuyen
                'Lấy Thông Tin Tiền Hàng
                Dim dtThongTinTienHang As New DataTable
                dtThongTinTienHang = ThongTinTienDonHang()
                Dim newRow As DataRow
                newRow = dtThongTinTienHang.NewRow
                Dim TongTienThanhToan As Double = 0
                TongTienThanhToan = TongTienHang + ThueVAT
                newRow.Item("TienHang") = TongTienHang.ToString("N", VietNam)
                newRow.Item("ThueGTGT") = ThueVAT.ToString("N", VietNam)
                newRow.Item("ThueSuatGTGT") = ThueSuatVAT '.ToString
                newRow.Item("TongThanhToan") = TongTienThanhToan.ToString("N", VietNam)
                Dim doctien As String = ""
                If comboTien.SelectedValue = "VND" Then
                    doctien = Num2Text(LamTron(TongTienThanhToan, 0))
                ElseIf comboTien.SelectedValue = "USD" Then
                    'Tách ra phần USD và phần cents
                    Dim Tien As String = LamTron(TongTienThanhToan, 2).ToString()
                    Dim aTien() As String = Tien.Split(".")
                    Dim TienChan As Integer
                    Dim TienLe As Integer
                    If aTien.Length = 2 Then
                        TienChan = Integer.Parse(aTien(0))
                        TienLe = Integer.Parse(aTien(1))
                        doctien = Num2Text(TienChan).Replace("đồng", "") & " USD " & Num2Text(TienLe).Replace("đồng", "").ToLower() & " cents"
                    ElseIf aTien.Length = 1 Then
                        TienChan = Integer.Parse(aTien(0))
                        doctien = Num2Text(TienChan).Replace("đồng", "") & " USD"
                    End If
                ElseIf comboTien.SelectedValue = "SGD" Then
                    'Tách ra phần USD và phần cents
                    Dim Tien As String = LamTron(TongTienThanhToan, 2).ToString()
                    Dim aTien() As String = Tien.Split(".")
                    Dim TienChan As Integer
                    Dim TienLe As Integer
                    If aTien.Length = 2 Then
                        TienChan = Integer.Parse(aTien(0))
                        TienLe = Integer.Parse(aTien(1))
                        doctien = Num2Text(TienChan).Replace("đồng", "") & " SGD " & Num2Text(TienLe).Replace("đồng", "").ToLower() & " cents"
                    ElseIf aTien.Length = 1 Then
                        TienChan = Integer.Parse(aTien(0))
                        doctien = Num2Text(TienChan).Replace("đồng", "") & " SGD"
                    End If
                End If
                newRow.Item("TienBangChu") = doctien
                dtThongTinTienHang.Rows.Add(newRow)
                If cbxNoPrintMoney.Checked Then
                    objReport_KhongTien.Database.Tables("ThongTinTienDonHang").SetDataSource(dtThongTinTienHang)
                Else
                    objReport.Database.Tables("ThongTinTienDonHang").SetDataSource(dtThongTinTienHang)
                End If

                Dim DonGia As Double
                For i As Integer = 0 To dtChiTietDonHangBan.Rows.Count - 1
                    If dtChiTietDonHangBan.Rows(i)("LoaiPhi") = "GiamTru" Then
                        DonGia = Double.Parse(dtChiTietDonHangBan.Rows(i)("DonGiaDec"))
                        If DonGia <= 100 Then
                            dtChiTietDonHangBan.Rows(i)("TenSanPham") = dtChiTietDonHangBan.Rows(i)("MaSanPham") & " (" & DonGia & "%)"
                        Else
                            dtChiTietDonHangBan.Rows(i)("TenSanPham") = dtChiTietDonHangBan.Rows(i)("MaSanPham")
                        End If
                        dtChiTietDonHangBan.Rows(i)("DonGia") = ""
                    Else
                        dtChiTietDonHangBan.Rows(i)("DonGia") = Convert.ToDouble(dtChiTietDonHangBan.Rows(i)("DonGiaDec")).ToString("N", VietNam).ToString()
                    End If
                    'format dongia
                    dtChiTietDonHangBan.Rows(i)("ThanhTien") = Convert.ToDouble(dtChiTietDonHangBan.Rows(i)("ThanhTien")).ToString("N", VietNam).ToString()
                Next
                ''Phát Sinh các row trắng
                Dim emptyRow As DataRow
                For i As Integer = 1 To 12 - dtChiTietDonHangBan.Rows.Count
                    emptyRow = dtChiTietDonHangBan.NewRow
                    dtChiTietDonHangBan.Rows.Add(emptyRow)
                    'dtChiTietDonHangBan.AcceptChanges()
                Next
                If cbxNoPrintMoney.Checked Then
                    objReport_KhongTien.Database.Tables("ChiTietDonHangBan").SetDataSource(dtChiTietDonHangBan)
                Else
                    objReport.Database.Tables("ChiTietDonHangBan").SetDataSource(dtChiTietDonHangBan)
                End If
                'Thông tin khách hàng
                Dim dtThongTinKhachHang As New DataTable
                query = "Select * From DonHangBan Where IDDonHangBan=" & IDDonHangBan
                adapter = New OleDb.OleDbDataAdapter(query, dbConn)
                adapter.Fill(dtThongTinKhachHang)
                If dtThongTinKhachHang.Rows(0)("NhanVienTiepThi") = "Chưa có" Then
                    dtThongTinKhachHang.Rows(0)("NhanVienTiepThi") = ""
                End If
                If cbxNoPrintMoney.Checked Then
                    objReport_KhongTien.Database.Tables("ThongTinKhachHang").SetDataSource(dtThongTinKhachHang)
                Else
                    objReport.Database.Tables("ThongTinKhachHang").SetDataSource(dtThongTinKhachHang)
                End If
                'Thông Tin Ngày Hóa Đơn 
                Dim dsNgay As New dsNgay
                Dim dtNgay As New DataTable
                dtNgay = dsNgay.Tables(0)
                Dim dateRow As DataRow
                dateRow = dtNgay.NewRow
                dateRow.Item("Ngay") = dtpNgayHopDong.Value.ToShortDateString()
                formatDateVN2String_In(dateRow.Item("Ngay"))
                dtNgay.Rows.Add(dateRow)
                If cbxNoPrintMoney.Checked Then
                    objReport_KhongTien.Database.Tables("dtNgay").SetDataSource(CType(dtNgay, DataTable))
                Else
                    objReport.Database.Tables("dtNgay").SetDataSource(CType(dtNgay, DataTable))
                End If
                If cbxNoPrintMoney.Checked Then
                    objReport_KhongTien.PrintOptions.PrinterName = Printer()
                    objReport_KhongTien.PrintToPrinter(1, False, 1, 1)
                Else
                    objReport.PrintOptions.PrinterName = Printer()
                    objReport.PrintToPrinter(1, False, 1, 1)
                End If
            Catch ex As Exception

            End Try
        End Sub

        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Xem trước đơn hàng
        ''' </summary>
        ''' <remarks>
        ''' 
        ''' </remarks>
        ''' <history>
        '''   [lamtn] 18/02/2011  Created
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Private Sub Order_PrintPreview()
            Try
                Dim dtChiTietDonHangBan As DataTable
                dtChiTietDonHangBan = InitOrderTable()
                Dim DHRow As DataRow
                ' Lưu thông tin chi tiết đơn hàng
                For i As Integer = 0 To dgvSanPhamHopdong_Tab1.Rows.Count - 1
                    DHRow = dtChiTietDonHangBan.NewRow
                    DHRow.Item("IDSanPham") = dgvSanPhamHopdong_Tab1("IDSanPham", i).Value
                    DHRow.Item("MaSanPham") = dgvSanPhamHopdong_Tab1("MaHang", i).Value
                    DHRow.Item("TenSanPham") = dgvSanPhamHopdong_Tab1("TenHang", i).Value
                    DHRow.Item("TenQuyCach") = dgvSanPhamHopdong_Tab1("DonViTinh", i).Value
                    DHRow.Item("DonGia") = dgvSanPhamHopdong_Tab1("DonGia", i).Value
                    DHRow.Item("SoLuong") = dgvSanPhamHopdong_Tab1("SoLuong", i).Value
                    DHRow.Item("ThanhTien") = dgvSanPhamHopdong_Tab1("ThanhTien", i).Value
                    DHRow.Item("LoaiPhi") = dgvSanPhamHopdong_Tab1("LoaiPhi", i).Value
                    dtChiTietDonHangBan.Rows.Add(DHRow)
                Next
                'Lấy Thông Tin Tiền Hàng
                Dim dtThongTinTienHang As New DataTable
                dtThongTinTienHang = ThongTinTienDonHang()
                Dim newRow As DataRow
                newRow = dtThongTinTienHang.NewRow

                Dim TongTienHangHoa As Double = 0
                Dim TongTienGiamTru As Double = 0
                Dim TongTienHang As Double = 0
                Dim ThueSuatVAT As Double = 0
                ThueSuatVAT = Double.Parse(txtVat.Text.Trim)

                TongTienHangHoa = TinhTongTienHangHoa(dtChiTietDonHangBan)
                TongTienGiamTru = TinhTongTienGiamTru(dtChiTietDonHangBan)
                TongTienHang = TongTienHangHoa - TongTienGiamTru
                Dim ThueVAT As Double = 0
                ThueVAT = (ThueSuatVAT * TongTienHang) / 100

                Dim TongTienThanhToan As Double = 0
                Dim sThongThanhToan As String = ""
                TongTienThanhToan = Convert.ToDouble(TongTienHang + ThueVAT)
                'sThongThanhToan = CInt(TongTienThanhToan.ToString).ToString("N", Globalization.CultureInfo.CreateSpecificCulture("en-us")).ToString()
                newRow.Item("TienHang") = TongTienHang.ToString("N", VietNam)
                newRow.Item("ThueGTGT") = ThueVAT.ToString("N", VietNam)
                newRow.Item("ThueSuatGTGT") = ThueSuatVAT.ToString & " %"
                newRow.Item("TongThanhToan") = TongTienThanhToan.ToString("N", VietNam)
                Dim doctien As String = ""
                If comboTien.SelectedValue = "VND" Then
                    doctien = Num2Text(LamTron(TongTienThanhToan, 0))
                ElseIf comboTien.SelectedValue = "USD" Then
                    'Tách ra phần USD và phần cents
                    Dim Tien As String = LamTron(TongTienThanhToan, 2).ToString()
                    Dim aTien() As String = Tien.Split(".")
                    Dim TienChan As Integer
                    Dim TienLe As Integer
                    If aTien.Length = 2 Then
                        TienChan = Integer.Parse(aTien(0))
                        TienLe = Integer.Parse(aTien(1))
                        doctien = Num2Text(TienChan).Replace("đồng", "") & " USD " & Num2Text(TienLe).Replace("đồng", "").ToLower() & " cents"
                    ElseIf aTien.Length = 1 Then
                        TienChan = Integer.Parse(aTien(0))
                        doctien = Num2Text(TienChan).Replace("đồng", "") & " USD"
                    End If
                ElseIf comboTien.SelectedValue = "SGD" Then
                    'Tách ra phần USD và phần cents
                    Dim Tien As String = LamTron(TongTienThanhToan, 2).ToString()
                    Dim aTien() As String = Tien.Split(".")
                    Dim TienChan As Integer
                    Dim TienLe As Integer
                    If aTien.Length = 2 Then
                        TienChan = Integer.Parse(aTien(0))
                        TienLe = Integer.Parse(aTien(1))
                        doctien = Num2Text(TienChan).Replace("đồng", "") & " SGD " & Num2Text(TienLe).Replace("đồng", "").ToLower() & " cents"
                    ElseIf aTien.Length = 1 Then
                        TienChan = Integer.Parse(aTien(0))
                        doctien = Num2Text(TienChan).Replace("đồng", "") & " SGD"
                    End If
                End If
                newRow.Item("TienBangChu") = doctien
                'If TongTienThanhToan > 0 Then

                'Else
                '    newRow.Item("TienBangChu") = "{ Nợ } " & Num2Text(sThongThanhToan.Replace("-", ""))
                'End If
                dtThongTinTienHang.Rows.Add(newRow)
                'dtThongTinTienHang.AcceptChanges()
                'For i As Integer = 0 To dtThongTinTienHang.Rows.Count - 1
                '    dtThongTinTienHang.Rows(i)("TienHang") = CInt(dtThongTinTienHang.Rows(i)("TienHang").ToString).ToString("N", Globalization.CultureInfo.CreateSpecificCulture("vi-vn")).ToString()
                '    dtThongTinTienHang.Rows(i)("ThueGTGT") = CInt(dtThongTinTienHang.Rows(i)("ThueGTGT").ToString).ToString("N", Globalization.CultureInfo.CreateSpecificCulture("vi-vn")).ToString()
                '    dtThongTinTienHang.Rows(i)("TongThanhToan") = CInt(dtThongTinTienHang.Rows(i)("TongThanhToan").ToString).ToString("N", Globalization.CultureInfo.CreateSpecificCulture("vi-vn")).ToString()
                'Next
                '-Format
                Dim DonGia As Double
                Dim IDSanPham As String
                For i As Integer = 0 To dtChiTietDonHangBan.Rows.Count - 1
                    IDSanPham = dtChiTietDonHangBan.Rows(i)("IDSanPham")
                    If Not (String.IsNullOrEmpty(IDSanPham) Or IsDBNull(IDSanPham) Or IDSanPham = "0") Then
                        If dtChiTietDonHangBan.Rows(i)("LoaiPhi") = "GiamTru" Then
                            DonGia = Double.Parse(dtChiTietDonHangBan.Rows(i)("DonGia"))
                            If DonGia <= 100 Then
                                dtChiTietDonHangBan.Rows(i)("TenSanPham") = dtChiTietDonHangBan.Rows(i)("MaSanPham") & " (" & DonGia & "%)"
                            Else
                                dtChiTietDonHangBan.Rows(i)("TenSanPham") = dtChiTietDonHangBan.Rows(i)("MaSanPham")
                            End If
                            dtChiTietDonHangBan.Rows(i)("DonGia") = ""
                        Else
                            dtChiTietDonHangBan.Rows(i)("DonGia") = Convert.ToDouble(dtChiTietDonHangBan.Rows(i)("DonGia").ToString).ToString("N", VietNam)
                        End If
                        dtChiTietDonHangBan.Rows(i)("ThanhTien") = Convert.ToDouble(dtChiTietDonHangBan.Rows(i)("ThanhTien").ToString).ToString("N", VietNam)
                    End If
                Next
                'Lưu thông tin khách hàng
                Dim dtThongTinKhachHang As DataTable
                dtThongTinKhachHang = InitCustomerTable()
                Dim customerRow As DataRow
                customerRow = dtThongTinKhachHang.NewRow
                customerRow.Item("TenKhachHang") = txtTenKhachHang.Text.Trim
                customerRow.Item("DiaChi") = txtDiaChi.Text.Trim
                customerRow.Item("MaSoThue") = txtMaSoThue.Text.Trim
                customerRow.Item("HinhThucThanhToan") = txtHinhThucThanhToan.Text.Trim
                'Kiểm tra hình thức tiếp thị
                If lblDaiLyId.Text = "0" Or lblDaiLyId.Text = "" Then
                    customerRow.Item("NhanVienTiepThi") = cbxNhanVienTT.Text
                Else

                    customerRow.Item("NhanVienTiepThi") = txtDaiLy.Text
                End If
                dtThongTinKhachHang.Rows.Add(customerRow)
                'Ngay
                Dim dsNgay As New dsNgay
                Dim dtNgay As New DataTable
                dtNgay = dsNgay.Tables(0)
                Dim dateRow As DataRow
                dateRow = dtNgay.NewRow
                dateRow.Item("Ngay") = dtpNgayHopDong.Value.ToShortDateString()
                formatDateVN2String_print(dateRow.Item("Ngay"))
                dtNgay.Rows.Add(dateRow)
                frmXemHoaDon.dtChiTietDonHangBan = dtChiTietDonHangBan
                frmXemHoaDon.dtNgay = dtNgay
                frmXemHoaDon.dtThongTinKhachHang = dtThongTinKhachHang
                frmXemHoaDon.dtThongTinTienHang = dtThongTinTienHang
                frmXemHoaDon.Show()
            Catch ex As Exception

            End Try
        End Sub
        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Xóa thông tin hóa đơn để nhập lại
        ''' </summary>
        ''' <remarks>
        ''' 
        ''' </remarks>
        ''' <history>
        '''   [lamtn] 18/02/2011  Created
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Private Sub Order_Clear()
            Try
                cmdLuu.Enabled = True
                cmdIn.Enabled = True
                TaoSoHoaDon()
                txtHoTenNguoiMua.Text = ""
                txtTenKhachHang.Text = ""
                txtDiaChi.Text = ""
                txtMaSoThue.Text = ""
                txtMaKhachHang.Text = ""
                txtHinhThucThanhToan.Text = ""
                txtCongTienHang.Text = ""
                txtTienThueVAT.Text = ""
                txtTongThanhToan.Text = ""
                dtpNgayHopDong.Value = Now
                txtPhiVanChuyen.Value = 0
                cbxNoPrintMoney.Checked = False
                comboTien_Load()
                cbxEditVat.Checked = False
                txtVat.Value = 10
                'txtTienVietBangChu.Text = ""
                IdDonHangBan_Edit = 0
                lblKhachHangId.Text = ""
                rbtNhanVienTiepThi.Checked = True
                rbtDaiLy.Checked = False
                txtDaiLy.Text = ""
                lblDaiLyId.Text = ""
                txtGhiChu.Text = ""
                cbxTruKho.Checked = True
                InitOrder()
                DaTruKho = False
                cbxTinhDoanhThu.Checked = True
                Report_TheoNgay()
            Catch ex As Exception

            End Try
        End Sub
        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Chỉnh sửa thông tin hóa đơn
        ''' </summary>
        ''' <remarks>
        ''' 
        ''' </remarks>
        ''' <history>
        '''   [lamtn] 18/02/2011  Created
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Private Sub Order_Edit()
            Try
                Dim IdDonHangBan As Integer = Integer.Parse(dgvKhachHang.Rows(dgvKhachHang.CurrentCell.RowIndex).Cells("IdDonHangBan").Value.ToString)
                Dim dbConn As New OleDb.OleDbConnection
                Dim dataAccess As New DataAccess
                Dim dbCommand As OleDb.OleDbCommand
                dataAccess.ConnectDatabase_DBAccess(dbConn)
                'Trạng Thái Đơn Hàng 
                Dim TrangThai As String
                dbCommand = New OleDbCommand("spDonHangBan_TrangThai", dbConn)
                dbCommand.CommandType = CommandType.StoredProcedure
                dbCommand.Parameters.Add("@IDDonHangBan", OleDbType.Integer).Value = IdDonHangBan
                TrangThai = dbCommand.ExecuteScalar()
                If TrangThai = "Đã duyệt" Then
                    cbxTruKho.Checked = True
                ElseIf TrangThai = "Chưa duyệt" Then
                    cbxTruKho.Checked = False
                    'DaTruKho = False
                End If
                '
                TabControl1.SelectedTab = cmdXemThongTinChiTiet
                'Thong Tin Don Hang spDonHangBan_DonHang
                Dim dtDonHang As New DataTable
                dbCommand = New OleDbCommand("spDonHangBan_DonHang", dbConn)
                dbCommand.CommandType = CommandType.StoredProcedure
                dbCommand.Parameters.Add("@IDDonHangBan", OleDbType.VarWChar).Value = IdDonHangBan
                Dim adapter As OleDb.OleDbDataAdapter
                adapter = New OleDb.OleDbDataAdapter(dbCommand)
                adapter.Fill(dtDonHang)
                'Thong Tin Khach Hang
                txtHoTenNguoiMua.Text = dtDonHang.Rows(0)("TenNguoiMua")
                txtTenKhachHang.Text = dtDonHang.Rows(0)("TenKhachHang")
                lblKhachHangId.Text = dtDonHang.Rows(0)("KhachHangId")
                txtDiaChi.Text = dtDonHang.Rows(0)("DiaChi")
                txtMaSoThue.Text = dtDonHang.Rows(0)("MaSoThue")
                dtpNgayHopDong.Value = dtDonHang.Rows(0)("NgayBan")
                txtMaKhachHang.Text = dtDonHang.Rows(0)("CodeKhachHang")
                txtHinhThucThanhToan.Text = dtDonHang.Rows(0)("HinhThucThanhToan")
                txtSo.Text = dtDonHang.Rows(0)("So")
                cbxNoPrintMoney.Checked = IIf(dtDonHang.Rows(0)("HoaDonTang") = 1, True, False)
                txtPhiVanChuyen.Value = dtDonHang.Rows(0)("PhiVanChuyen")
                txtGhiChu.Text = IIf(IsDBNull(dtDonHang.Rows(0)("GhiChu")), "", dtDonHang.Rows(0)("GhiChu"))
                cbxTinhDoanhThu.Checked = dtDonHang.Rows(0)("TinhDoanhThu")
                'tien
                If dtDonHang.Rows(0)("Tien") = "VND" Then
                    comboTien.SelectedIndex = 0
                ElseIf dtDonHang.Rows(0)("Tien") = "USD" Then
                    comboTien.SelectedIndex = 1
                Else : dtDonHang.Rows(0)("Tien") = "SGD"
                    comboTien.SelectedIndex = 2
                End If

                'Kiem Tra Tiep Thi
                If dtDonHang.Rows(0)("HinhThucTiepThi") = "Đại lý" Then
                    rbtDaiLy.Checked = True
                    rbtNhanVienTiepThi.Checked = False
                    txtDaiLy.Text = dtDonHang.Rows(0)("NhanVienTiepThi")
                    lblDaiLyId.Text = dtDonHang.Rows(0)("NhanVienTiepThiId")
                Else
                    rbtDaiLy.Checked = False
                    rbtNhanVienTiepThi.Checked = True
                    cbxNhanVienTT.SelectedValue = dtDonHang.Rows(0)("NhanVienTiepThiId")
                End If
                txtVat.Text = dtDonHang.Rows(0)("ThueVat")
                'Thong Tin Chi Tiet Don Hang spDonHangBan_ChiTietDonHang
                'khoi tao lai
                dtSanPhamHD = InitOrderTable()
                Dim newRow As DataRow
                Dim dtChiTietDonHang As New DataTable
                dbCommand = New OleDbCommand("spDonHangBan_ChiTietDonHang", dbConn)
                dbCommand.CommandType = CommandType.StoredProcedure
                dbCommand.Parameters.Add("@IDDonHangBan", OleDbType.Integer).Value = IdDonHangBan
                adapter = New OleDb.OleDbDataAdapter(dbCommand)
                adapter.Fill(dtChiTietDonHang)

                For i As Integer = 0 To dtChiTietDonHang.Rows.Count - 1
                    newRow = dtSanPhamHD.NewRow
                    newRow.Item("IDSanPham") = dtChiTietDonHang.Rows(i)("IdSanPham")
                    newRow.Item("MaSanPham") = dtChiTietDonHang.Rows(i)("MaSanPham")
                    newRow.Item("TenSanPham") = dtChiTietDonHang.Rows(i)("TenSanPham")
                    newRow.Item("TenQuyCach") = dtChiTietDonHang.Rows(i)("TenQuyCach")
                    newRow.Item("SoLuong") = dtChiTietDonHang.Rows(i)("SoLuong")
                    newRow.Item("DonGia") = dtChiTietDonHang.Rows(i)("DonGia")
                    newRow.Item("ThanhTien") = dtChiTietDonHang.Rows(i)("ThanhTien")
                    newRow.Item("LoaiPhi") = dtChiTietDonHang.Rows(i)("LoaiPhi")
                    newRow.Item("IsManyPrice") = dtChiTietDonHang.Rows(i)("IsManyPrice")
                    dtSanPhamHD.Rows.Add(newRow)
                Next
                'Phat Sinh Dong Trang
                Dim iRowEmpty As Integer = 12 - dtChiTietDonHang.Rows.Count - 1
                For i As Integer = 0 To iRowEmpty
                    newRow = dtSanPhamHD.NewRow
                    newRow.Item("IDSanPham") = 0
                    newRow.Item("MaSanPham") = ""
                    newRow.Item("TenSanPham") = ""
                    newRow.Item("TenQuyCach") = ""
                    newRow.Item("SoLuong") = ""
                    newRow.Item("DonGia") = ""
                    newRow.Item("ThanhTien") = ""
                    newRow.Item("LoaiPhi") = ""
                    dtSanPhamHD.Rows.Add(newRow)
                Next
                IdDonHangBan_Edit = IdDonHangBan
                dtSanPhamHD.DefaultView.Sort = "LoaiPhi DESC"
                Dim listPrice As New List(Of String)
                Dim comboxPrice As New DataGridViewComboBoxCell
                For i As Integer = 0 To 11
                    dgvSanPhamHopdong_Tab1("IDSanPham", i).Value = dtSanPhamHD.Rows(i)("IDSanPham")
                    dgvSanPhamHopdong_Tab1("MaHang", i).Value = dtSanPhamHD.Rows(i)("MaSanPham")
                    dgvSanPhamHopdong_Tab1("TenHang", i).Value = dtSanPhamHD.Rows(i)("TenSanPham")
                    dgvSanPhamHopdong_Tab1("DonViTinh", i).Value = dtSanPhamHD.Rows(i)("TenQuyCach")
                    If dgvSanPhamHopdong_Tab1("MaHang", i).Value <> "" Then
                        If dtSanPhamHD.Rows(i)("IsManyPrice") = "1" Then
                            'Nhieu gia
                            'Lay Het Gia Len
                            listPrice = New List(Of String)
                            Dim dtListPrice As New DataTable
                            dbCommand = New OleDbCommand("spGetPriceByCustomerAndID", dbConn)
                            dbCommand.CommandType = CommandType.StoredProcedure
                            dbCommand.Parameters.Add("@KhachHangId", OleDbType.Integer).Value = lblKhachHangId.Text.Trim
                            dbCommand.Parameters.Add("@IDSanPham", OleDbType.VarWChar).Value = dtSanPhamHD.Rows(i)("IDSanPham")
                            adapter = New OleDb.OleDbDataAdapter(dbCommand)
                            adapter.Fill(dtListPrice)
                            For j As Integer = 0 To dtListPrice.Rows.Count - 1
                                listPrice.Add(dtListPrice.Rows(j)("DonGia"))
                            Next
                            comboxPrice = CType(dgvSanPhamHopdong_Tab1("DonGia", i), DataGridViewComboBoxCell)
                            comboxPrice.DisplayStyle = DataGridViewComboBoxDisplayStyle.ComboBox
                            comboxPrice.DataSource = listPrice
                            comboxPrice.Value = dtSanPhamHD.Rows(i)("DonGia")
                            dgvSanPhamHopdong_Tab1("SoLuong", i).Value = dtSanPhamHD.Rows(i)("SoLuong")
                            If comboTien.SelectedValue = "VND" Then
                                dgvSanPhamHopdong_Tab1("ThanhTien", i).Value = LamTron(dtSanPhamHD.Rows(i)("ThanhTien"), 0).ToString("N02", US)
                            ElseIf comboTien.SelectedValue = "USD" Or comboTien.SelectedValue = "SGD" Then
                                dgvSanPhamHopdong_Tab1("ThanhTien", i).Value = LamTron(dtSanPhamHD.Rows(i)("ThanhTien"), 2).ToString("N02", US)
                            End If
                            dgvSanPhamHopdong_Tab1("LoaiPhi", i).Value = dtSanPhamHD.Rows(i)("LoaiPhi")
                            dgvSanPhamHopdong_Tab1("IsManyPrice", i).Value = dtSanPhamHD.Rows(i)("IsManyPrice")
                            dgvSanPhamHopdong_Tab1.Rows(i).DefaultCellStyle.BackColor = Color.Aquamarine
                        Else
                            listPrice = New List(Of String)
                            listPrice.Add(dtSanPhamHD.Rows(i)("DonGia"))
                            comboxPrice = CType(dgvSanPhamHopdong_Tab1("DonGia", i), DataGridViewComboBoxCell)
                            comboxPrice.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing
                            comboxPrice.DataSource = listPrice
                            comboxPrice.Value = dtSanPhamHD.Rows(i)("DonGia")
                            dgvSanPhamHopdong_Tab1("SoLuong", i).Value = dtSanPhamHD.Rows(i)("SoLuong")
                            If comboTien.SelectedValue = "VND" Then
                                dgvSanPhamHopdong_Tab1("ThanhTien", i).Value = LamTron(dtSanPhamHD.Rows(i)("ThanhTien"), 0).ToString("N02", US)
                            ElseIf comboTien.SelectedValue = "USD" Or comboTien.SelectedValue = "SGD" Then
                                dgvSanPhamHopdong_Tab1("ThanhTien", i).Value = LamTron(dtSanPhamHD.Rows(i)("ThanhTien"), 2).ToString("N02", US)
                            End If
                            dgvSanPhamHopdong_Tab1("LoaiPhi", i).Value = dtSanPhamHD.Rows(i)("LoaiPhi")
                            dgvSanPhamHopdong_Tab1("IsManyPrice", i).Value = dtSanPhamHD.Rows(i)("IsManyPrice")
                            dgvSanPhamHopdong_Tab1.Rows(i).DefaultCellStyle.BackColor = Color.White
                        End If
                    Else
                        listPrice = New List(Of String)
                        listPrice.Add("")
                        comboxPrice = CType(dgvSanPhamHopdong_Tab1("DonGia", i), DataGridViewComboBoxCell)
                        comboxPrice.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing
                        comboxPrice.DataSource = listPrice
                        comboxPrice.Value = ""
                        dgvSanPhamHopdong_Tab1("SoLuong", i).Value = ""
                        dgvSanPhamHopdong_Tab1("ThanhTien", i).Value = ""
                        dgvSanPhamHopdong_Tab1("LoaiPhi", i).Value = dtSanPhamHD.Rows(i)("LoaiPhi")
                        dgvSanPhamHopdong_Tab1("IsManyPrice", i).Value = dtSanPhamHD.Rows(i)("IsManyPrice")
                    End If
                Next
                dbConn.Close()
                TinhTienHangChuaThue()
                TinhTienThueVAT()
                TinhTienThueDaThue()
                'ChinhSua
                EditMode = 1
            Catch ex As Exception
                MessageBox.Show(ex.ToString)
            End Try
        End Sub
        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Chỉnh sửa thông tin hóa đơn
        ''' </summary>
        ''' <remarks>
        ''' 
        ''' </remarks>
        ''' <history>
        '''   [lamtn] 18/02/2011  Created
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Private Sub Order_KeThua()
            Try
                Dim IdDonHangBan As Integer = Integer.Parse(dgvKhachHang.Rows(dgvKhachHang.CurrentCell.RowIndex).Cells("IdDonHangBan").Value.ToString)
                Dim dbConn As New OleDb.OleDbConnection
                Dim dataAccess As New DataAccess
                Dim dbCommand As OleDb.OleDbCommand
                dataAccess.ConnectDatabase_DBAccess(dbConn)
                'Trạng Thái Đơn Hàng 
                Dim TrangThai As String
                dbCommand = New OleDbCommand("spDonHangBan_TrangThai", dbConn)
                dbCommand.CommandType = CommandType.StoredProcedure
                dbCommand.Parameters.Add("@IDDonHangBan", OleDbType.Integer).Value = IdDonHangBan
                TrangThai = dbCommand.ExecuteScalar()
                If TrangThai = "Đã duyệt" Then
                    cbxTruKho.Checked = True
                ElseIf TrangThai = "Chưa duyệt" Then
                    cbxTruKho.Checked = False
                    'DaTruKho = False
                End If
                '
                TabControl1.SelectedTab = cmdXemThongTinChiTiet
                'Thong Tin Don Hang spDonHangBan_DonHang
                Dim dtDonHang As New DataTable
                dbCommand = New OleDbCommand("spDonHangBan_DonHang", dbConn)
                dbCommand.CommandType = CommandType.StoredProcedure
                dbCommand.Parameters.Add("@IDDonHangBan", OleDbType.VarWChar).Value = IdDonHangBan
                Dim adapter As OleDb.OleDbDataAdapter
                adapter = New OleDb.OleDbDataAdapter(dbCommand)
                adapter.Fill(dtDonHang)
                'Thong Tin Khach Hang
                txtHoTenNguoiMua.Text = dtDonHang.Rows(0)("TenNguoiMua")
                txtTenKhachHang.Text = dtDonHang.Rows(0)("TenKhachHang")
                lblKhachHangId.Text = dtDonHang.Rows(0)("KhachHangId")
                txtDiaChi.Text = dtDonHang.Rows(0)("DiaChi")
                txtMaSoThue.Text = dtDonHang.Rows(0)("MaSoThue")
                dtpNgayHopDong.Value = dtDonHang.Rows(0)("NgayBan")
                txtMaKhachHang.Text = dtDonHang.Rows(0)("CodeKhachHang")
                txtHinhThucThanhToan.Text = dtDonHang.Rows(0)("HinhThucThanhToan")
                TaoSoHoaDon()
                cbxNoPrintMoney.Checked = IIf(dtDonHang.Rows(0)("HoaDonTang") = 1, True, False)
                txtPhiVanChuyen.Value = dtDonHang.Rows(0)("PhiVanChuyen")
                IIf(IsDBNull(dtDonHang.Rows(0)("GhiChu")), "", dtDonHang.Rows(0)("GhiChu"))
                'tien
                If dtDonHang.Rows(0)("Tien") = "VND" Then
                    comboTien.SelectedIndex = 0
                ElseIf dtDonHang.Rows(0)("Tien") = "USD" Then
                    comboTien.SelectedIndex = 1
                Else : dtDonHang.Rows(0)("Tien") = "SGD"
                    comboTien.SelectedIndex = 2
                End If

                'Kiem Tra Tiep Thi
                If dtDonHang.Rows(0)("HinhThucTiepThi") = "Đại lý" Then
                    rbtDaiLy.Checked = True
                    rbtNhanVienTiepThi.Checked = False
                    txtDaiLy.Text = dtDonHang.Rows(0)("NhanVienTiepThi")
                    lblDaiLyId.Text = dtDonHang.Rows(0)("NhanVienTiepThiId")
                Else
                    rbtDaiLy.Checked = False
                    rbtNhanVienTiepThi.Checked = True
                    cbxNhanVienTT.SelectedValue = dtDonHang.Rows(0)("NhanVienTiepThiId")
                End If
                txtVat.Text = dtDonHang.Rows(0)("ThueVat")
                'Thong Tin Chi Tiet Don Hang spDonHangBan_ChiTietDonHang
                'khoi tao lai
                dtSanPhamHD = InitOrderTable()
                Dim newRow As DataRow
                Dim dtChiTietDonHang As New DataTable
                dbCommand = New OleDbCommand("spDonHangBan_ChiTietDonHang", dbConn)
                dbCommand.CommandType = CommandType.StoredProcedure
                dbCommand.Parameters.Add("@IDDonHangBan", OleDbType.Integer).Value = IdDonHangBan
                adapter = New OleDb.OleDbDataAdapter(dbCommand)
                adapter.Fill(dtChiTietDonHang)

                For i As Integer = 0 To dtChiTietDonHang.Rows.Count - 1
                    newRow = dtSanPhamHD.NewRow
                    newRow.Item("IDSanPham") = dtChiTietDonHang.Rows(i)("IdSanPham")
                    newRow.Item("MaSanPham") = dtChiTietDonHang.Rows(i)("MaSanPham")
                    newRow.Item("TenSanPham") = dtChiTietDonHang.Rows(i)("TenSanPham")
                    newRow.Item("TenQuyCach") = dtChiTietDonHang.Rows(i)("TenQuyCach")
                    newRow.Item("SoLuong") = dtChiTietDonHang.Rows(i)("SoLuong")
                    newRow.Item("DonGia") = dtChiTietDonHang.Rows(i)("DonGia")
                    newRow.Item("ThanhTien") = dtChiTietDonHang.Rows(i)("ThanhTien")
                    newRow.Item("LoaiPhi") = dtChiTietDonHang.Rows(i)("LoaiPhi")
                    newRow.Item("IsManyPrice") = dtChiTietDonHang.Rows(i)("IsManyPrice")
                    dtSanPhamHD.Rows.Add(newRow)
                Next
                'Phat Sinh Dong Trang
                Dim iRowEmpty As Integer = 12 - dtChiTietDonHang.Rows.Count - 1
                For i As Integer = 0 To iRowEmpty
                    newRow = dtSanPhamHD.NewRow
                    newRow.Item("IDSanPham") = 0
                    newRow.Item("MaSanPham") = ""
                    newRow.Item("TenSanPham") = ""
                    newRow.Item("TenQuyCach") = ""
                    newRow.Item("SoLuong") = ""
                    newRow.Item("DonGia") = ""
                    newRow.Item("ThanhTien") = ""
                    newRow.Item("LoaiPhi") = ""
                    dtSanPhamHD.Rows.Add(newRow)
                Next
                IdDonHangBan_Edit = IdDonHangBan
                dtSanPhamHD.DefaultView.Sort = "LoaiPhi DESC"
                Dim listPrice As New List(Of String)
                Dim comboxPrice As New DataGridViewComboBoxCell
                For i As Integer = 0 To 11
                    dgvSanPhamHopdong_Tab1("IDSanPham", i).Value = dtSanPhamHD.Rows(i)("IDSanPham")
                    dgvSanPhamHopdong_Tab1("MaHang", i).Value = dtSanPhamHD.Rows(i)("MaSanPham")
                    dgvSanPhamHopdong_Tab1("TenHang", i).Value = dtSanPhamHD.Rows(i)("TenSanPham")
                    dgvSanPhamHopdong_Tab1("DonViTinh", i).Value = dtSanPhamHD.Rows(i)("TenQuyCach")
                    If dgvSanPhamHopdong_Tab1("MaHang", i).Value <> "" Then
                        If dtSanPhamHD.Rows(i)("IsManyPrice") = "1" Then
                            'Nhieu gia
                            'Lay Het Gia Len
                            listPrice = New List(Of String)
                            Dim dtListPrice As New DataTable
                            dbCommand = New OleDbCommand("spGetPriceByCustomerAndID", dbConn)
                            dbCommand.CommandType = CommandType.StoredProcedure
                            dbCommand.Parameters.Add("@KhachHangId", OleDbType.Integer).Value = lblKhachHangId.Text.Trim
                            dbCommand.Parameters.Add("@IDSanPham", OleDbType.VarWChar).Value = dtSanPhamHD.Rows(i)("IDSanPham")
                            adapter = New OleDb.OleDbDataAdapter(dbCommand)
                            adapter.Fill(dtListPrice)
                            For j As Integer = 0 To dtListPrice.Rows.Count - 1
                                listPrice.Add(dtListPrice.Rows(j)("DonGia"))
                            Next
                            comboxPrice = CType(dgvSanPhamHopdong_Tab1("DonGia", i), DataGridViewComboBoxCell)
                            comboxPrice.DisplayStyle = DataGridViewComboBoxDisplayStyle.ComboBox
                            comboxPrice.DataSource = listPrice
                            comboxPrice.Value = dtSanPhamHD.Rows(i)("DonGia")
                            dgvSanPhamHopdong_Tab1("SoLuong", i).Value = dtSanPhamHD.Rows(i)("SoLuong")
                            If comboTien.SelectedValue = "VND" Then
                                dgvSanPhamHopdong_Tab1("ThanhTien", i).Value = LamTron(dtSanPhamHD.Rows(i)("ThanhTien"), 0).ToString("N02", US)
                            ElseIf comboTien.SelectedValue = "USD" Or comboTien.SelectedValue = "SGD" Then
                                dgvSanPhamHopdong_Tab1("ThanhTien", i).Value = LamTron(dtSanPhamHD.Rows(i)("ThanhTien"), 2).ToString("N02", US)
                            End If
                            dgvSanPhamHopdong_Tab1("LoaiPhi", i).Value = dtSanPhamHD.Rows(i)("LoaiPhi")
                            dgvSanPhamHopdong_Tab1("IsManyPrice", i).Value = dtSanPhamHD.Rows(i)("IsManyPrice")
                            dgvSanPhamHopdong_Tab1.Rows(i).DefaultCellStyle.BackColor = Color.Aquamarine
                        Else
                            listPrice = New List(Of String)
                            listPrice.Add(dtSanPhamHD.Rows(i)("DonGia"))
                            comboxPrice = CType(dgvSanPhamHopdong_Tab1("DonGia", i), DataGridViewComboBoxCell)
                            comboxPrice.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing
                            comboxPrice.DataSource = listPrice
                            comboxPrice.Value = dtSanPhamHD.Rows(i)("DonGia")
                            dgvSanPhamHopdong_Tab1("SoLuong", i).Value = dtSanPhamHD.Rows(i)("SoLuong")
                            If comboTien.SelectedValue = "VND" Then
                                dgvSanPhamHopdong_Tab1("ThanhTien", i).Value = LamTron(dtSanPhamHD.Rows(i)("ThanhTien"), 0).ToString("N02", US)
                            ElseIf comboTien.SelectedValue = "USD" Or comboTien.SelectedValue = "SGD" Then
                                dgvSanPhamHopdong_Tab1("ThanhTien", i).Value = LamTron(dtSanPhamHD.Rows(i)("ThanhTien"), 2).ToString("N02", US)
                            End If
                            dgvSanPhamHopdong_Tab1("LoaiPhi", i).Value = dtSanPhamHD.Rows(i)("LoaiPhi")
                            dgvSanPhamHopdong_Tab1("IsManyPrice", i).Value = dtSanPhamHD.Rows(i)("IsManyPrice")
                            dgvSanPhamHopdong_Tab1.Rows(i).DefaultCellStyle.BackColor = Color.White
                        End If
                    Else
                        listPrice = New List(Of String)
                        listPrice.Add("")
                        comboxPrice = CType(dgvSanPhamHopdong_Tab1("DonGia", i), DataGridViewComboBoxCell)
                        comboxPrice.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing
                        comboxPrice.DataSource = listPrice
                        comboxPrice.Value = ""
                        dgvSanPhamHopdong_Tab1("SoLuong", i).Value = ""
                        dgvSanPhamHopdong_Tab1("ThanhTien", i).Value = ""
                        dgvSanPhamHopdong_Tab1("LoaiPhi", i).Value = dtSanPhamHD.Rows(i)("LoaiPhi")
                        dgvSanPhamHopdong_Tab1("IsManyPrice", i).Value = dtSanPhamHD.Rows(i)("IsManyPrice")
                    End If
                Next
                dbConn.Close()
                TinhTienHangChuaThue()
                TinhTienThueVAT()
                TinhTienThueDaThue()
                'ChinhSua
                EditMode = 2
            Catch ex As Exception
                MessageBox.Show(ex.ToString)
            End Try
        End Sub
        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' In hóa đơn ở form thống kê
        ''' </summary>
        ''' <remarks>
        ''' 
        ''' </remarks>
        ''' <history>
        '''   [lamtn] 18/02/2011  Created
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Private Sub Order_Print2()
            Try
                Dim IdDonHangBan As Integer = Integer.Parse(dgvKhachHang.Rows(dgvKhachHang.CurrentCell.RowIndex).Cells("IdDonHangBan").Value.ToString)
                frmInHoaDon.IdDonHangBan = IdDonHangBan
                frmInHoaDon.Show()
            Catch ex As Exception

            End Try
        End Sub
        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Xóa hóa đơn
        ''' </summary>
        ''' <remarks>
        ''' 
        ''' </remarks>
        ''' <history>
        '''   [lamtn] 18/02/2011  Created
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Private Sub Order_Delete()
            Try
                Dim IDDonHangBan As Integer = Integer.Parse(dgvKhachHang.Rows(dgvKhachHang.CurrentCell.RowIndex).Cells("IDDonHangBan").Value.ToString)
                'check tình trạng, nếu đơn hàng đã duyệt thì không thể xóa
                Dim dbConn As New OleDb.OleDbConnection
                Dim dataAccess As New DataAccess
                Dim query As String
                dataAccess.ConnectDatabase_DBAccess(dbConn)
                Dim TrangThai As String = ""
                Dim dbCommand As OleDb.OleDbCommand
                query = "Select TrangThai From DonHangBan Where IdDonHangBan=" & IDDonHangBan
                dbCommand = New OleDbCommand(query, dbConn)
                TrangThai = dbCommand.ExecuteScalar()
                Dim dlgRes As DialogResult
                If TrangThai = "Đã duyệt" Then
                    dlgRes = MessageBox.Show("Đơn hàng đã được duyệt.Bạn không thể xóa đơn hàng này.Vui lòng kiểm tra thông tin trước khi thực hiện", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error)
                    dbConn.Close()
                    Exit Sub
                Else
                    dlgRes = MessageBox.Show( _
                          "Bạn muốn xóa thông tin đơn hàng này", _
                          "Thông báo", _
                    MessageBoxButtons.OKCancel, _
                          MessageBoxIcon.Question)
                    If dlgRes = Windows.Forms.DialogResult.OK Then
                        query = String.Format("Delete From DonHangBan Where IDDonHangBan={0};Delete From ChiTietDonHangBan Where IDDonHangBan={0}", IDDonHangBan)
                        dbCommand = New OleDb.OleDbCommand(query, dbConn)
                        dbCommand.ExecuteNonQuery()
                        dbConn.Close()
                        Select Case ReportType
                            Case 0
                                Report_TheoNgay()
                            Case 1
                                Report_TheoThang()
                            Case 2
                                Report_TheoNam()
                            Case 3
                                Report_TuNgayDenNgay()
                            Case Else
                                Report_TenKhachHang()
                        End Select
                    End If
                End If

            Catch ex As Exception

            End Try
        End Sub
        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Duyệt hóa đơn
        ''' </summary>
        ''' <remarks>
        ''' 
        ''' </remarks>
        ''' <history>
        '''   [lamtn] 18/02/2011  Created
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Private Sub Order_Approved()
            Try
                Dim IDDonHangBan As Integer = Integer.Parse(dgvKhachHang.Rows(dgvKhachHang.CurrentCell.RowIndex).Cells("IDDonHangBan").Value.ToString)
                'check tình trạng, nếu đơn hàng đã duyệt thì không thể xóa

                Dim dbConn As New OleDb.OleDbConnection
                Dim dataAccess As New DataAccess
                Dim query As String
                dataAccess.ConnectDatabase_DBAccess(dbConn)
                Dim TrangThai As String = ""
                Dim dbCommand As OleDb.OleDbCommand
                query = "Select TrangThai From DonHangBan Where IdDonHangBan=" & IDDonHangBan
                dbCommand = New OleDbCommand(query, dbConn)
                TrangThai = dbCommand.ExecuteScalar()
                If TrangThai = "Đã duyệt" Then
                    MessageBox.Show("Đơn hàng đã được duyệt.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Hand)
                    dbConn.Close()
                    Exit Sub
                End If
                Dim dlgRes As DialogResult
                dlgRes = MessageBox.Show( _
                          "Bạn đồng ý duyệt đơn hàng này?", _
                          "Thông báo", _
                    MessageBoxButtons.OKCancel, _
                          MessageBoxIcon.Question)
                If dlgRes = Windows.Forms.DialogResult.OK Then
                    query = String.Format("Update DonHangBan Set TrangThai=N'Đã duyệt' Where IDDonHangBan={0};Update ChiTietDonHangBan Set TrangThai=N'Đã duyệt' Where IDDonHangBan={0}", IDDonHangBan)
                    dbCommand = New OleDb.OleDbCommand(query, dbConn)
                    dbCommand.ExecuteNonQuery()
                    '----------Cập nhật số lượng tồn kho----------------
                    query = "Select IdSanPham,SoLuong From ChiTietDonHangBan Where LoaiPhi='HangHoa' And IDDonHangBan=" & IDDonHangBan
                    Dim dtSoLuongSP As New DataTable
                    Dim adapter As OleDb.OleDbDataAdapter
                    adapter = New OleDb.OleDbDataAdapter(query, dbConn)
                    adapter.Fill(dtSoLuongSP)
                    Dim SoLuongTru As Single
                    For i As Integer = 0 To dtSoLuongSP.Rows.Count - 1
                        SoLuongTru = Single.Parse(dtSoLuongSP.Rows(i)("SoLuong"))
                        query = "Update SanPham Set SoLuongTon = SoLuongTon - " & SoLuongTru & " Where IdSanPham=" & dtSoLuongSP.Rows(i)("IDSanPham")
                        dbCommand = New OleDbCommand(query, dbConn)
                        dbCommand.ExecuteNonQuery()
                    Next
                    dbConn.Close()
                    '
                    Select Case ReportType
                        Case 0
                            Report_TheoNgay()
                        Case 1
                            Report_TheoThang()
                        Case 2
                            Report_TheoNam()
                        Case 3
                            Report_TuNgayDenNgay()
                        Case Else
                            Report_TenKhachHang()
                    End Select
                End If
            Catch ex As Exception

            End Try
        End Sub
        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Hủy hóa đơn
        ''' </summary>
        ''' <remarks>
        ''' 
        ''' </remarks>
        ''' <history>
        '''   [lamtn] 18/02/2011  Created
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Private Sub Order_Cancel()
            Try
                Dim IDDonHangBan As Integer = Integer.Parse(dgvKhachHang.Rows(dgvKhachHang.CurrentCell.RowIndex).Cells("IDDonHangBan").Value.ToString)
                'check tình trạng, nếu đơn hàng đã duyệt thì không thể xóa

                Dim dbConn As New OleDb.OleDbConnection
                Dim dataAccess As New DataAccess
                Dim query As String
                dataAccess.ConnectDatabase_DBAccess(dbConn)
                Dim TrangThai As String = ""
                Dim dbCommand As OleDb.OleDbCommand
                query = "Select TrangThai From DonHangBan Where IdDonHangBan=" & IDDonHangBan
                dbCommand = New OleDbCommand(query, dbConn)
                TrangThai = dbCommand.ExecuteScalar()
                If TrangThai = "Đã hủy" Then
                    MessageBox.Show("Đơn hàng đã được hủy.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Hand)
                    dbConn.Close()
                    Exit Sub
                End If
                Dim dlgRes As DialogResult
                dlgRes = MessageBox.Show( _
                          "Bạn đồng ý hủy đơn hàng này?", _
                          "Thông báo", _
                    MessageBoxButtons.OKCancel, _
                          MessageBoxIcon.Question)
                If dlgRes = Windows.Forms.DialogResult.OK Then
                    query = String.Format("Update DonHangBan Set TrangThai=N'Đã hủy' Where IDDonHangBan={0};Update ChiTietDonHangBan Set TrangThai=N'Đã hủy' Where IDDonHangBan={0}", IDDonHangBan)
                    dbCommand = New OleDb.OleDbCommand(query, dbConn)
                    dbCommand.ExecuteNonQuery()
                    dbConn.Close()
                    '
                    Select Case ReportType
                        Case 0
                            Report_TheoNgay()
                        Case 1
                            Report_TheoThang()
                        Case 2
                            Report_TheoNam()
                        Case 3
                            Report_TuNgayDenNgay()
                        Case 4
                            Report_TenKhachHang()
                        Case 5
                            Report_SoHoaDon()
                    End Select
                End If
            Catch ex As Exception

            End Try
        End Sub
#End Region
        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Chỉnh sửa thông tin hóa đơn
        ''' </summary>
        ''' <remarks>
        ''' 
        ''' </remarks>
        ''' <history>
        '''   [lamtn] 18/02/2011  Created
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Private Sub Order_ViewByNumber(ByVal IdDonHangBan As Integer)
            Try
                'check tình trạng, nếu đơn hàng đã duyệt thì không thể xóa
                Dim dbConn As New OleDb.OleDbConnection
                Dim dataAccess As New DataAccess
                Dim query As String
                dataAccess.ConnectDatabase_DBAccess(dbConn)
                Dim TrangThai As String = ""
                Dim dbCommand As OleDb.OleDbCommand
                query = "Select TrangThai From DonHangBan Where IdDonHangBan=" & IdDonHangBan
                dbCommand = New OleDbCommand(query, dbConn)
                TrangThai = dbCommand.ExecuteScalar()
                '
                TabControl1.SelectedTab = cmdXemThongTinChiTiet
                'show info for edit
                Dim NgayBan As String = dtpTheoNgay.Value.ToString.Split(" ")(0)
                query = "Select * From DonHangBan Where IDDonHangBan=" & IdDonHangBan
                Dim dsThongKe As New DataSet
                Dim adapter As OleDb.OleDbDataAdapter
                adapter = New OleDb.OleDbDataAdapter(query, dbConn)
                adapter.Fill(dsThongKe)

                'Thong Tin Khach Hang
                txtSo.Text = dsThongKe.Tables(0).Rows(0)("So")
                txtHoTenNguoiMua.Text = dsThongKe.Tables(0).Rows(0)("TenNguoiMua")
                txtTenKhachHang.Text = dsThongKe.Tables(0).Rows(0)("TenKhachHang")
                lblKhachHangId.Text = dsThongKe.Tables(0).Rows(0)("KhachHangId")
                txtDiaChi.Text = dsThongKe.Tables(0).Rows(0)("DiaChi")
                txtMaSoThue.Text = dsThongKe.Tables(0).Rows(0)("MaSoThue")
                dtpNgayHopDong.Value = dsThongKe.Tables(0).Rows(0)("NgayBan")
                txtMaKhachHang.Text = dsThongKe.Tables(0).Rows(0)("CodeKhachHang")
                txtHinhThucThanhToan.Text = dsThongKe.Tables(0).Rows(0)("HinhThucThanhToan")
                'Kiem Tra Tiep Thi
                If dsThongKe.Tables(0).Rows(0)("HinhThucTiepThi") = "Đại lý" Then
                    rbtDaiLy.Checked = True
                    rbtNhanVienTiepThi.Checked = False
                    txtDaiLy.Text = dsThongKe.Tables(0).Rows(0)("NhanVienTiepThi")
                    lblDaiLyId.Text = dsThongKe.Tables(0).Rows(0)("NhanVienTiepThiId")
                Else
                    rbtDaiLy.Checked = False
                    rbtNhanVienTiepThi.Checked = True
                    cbxNhanVienTT.SelectedValue = dsThongKe.Tables(0).Rows(0)("NhanVienTiepThiId")
                End If
                txtVat.Text = dsThongKe.Tables(0).Rows(0)("ThueVat")
                'Thong Tin Don Hang
                'khoi tao lai
                dtSanPhamHD = InitOrderTable()
                Dim newRow As DataRow
                Dim dsDonHang As New DataSet
                Dim dtDonHang As New DataTable
                query = "Select * From ChiTietDonHangBan Where IdDonHangBan=" & IdDonHangBan
                adapter = New OleDb.OleDbDataAdapter(query, dbConn)
                adapter.Fill(dsDonHang)
                dtDonHang = dsDonHang.Tables(0)
                Dim strThanhTien As String
                For i As Integer = 0 To dtDonHang.Rows.Count - 1
                    newRow = dtSanPhamHD.NewRow
                    newRow.Item("RowIndex") = i + 1
                    newRow.Item("IDSanPham") = dtDonHang.Rows(i)("IdSanPham")
                    newRow.Item("MaSanPham") = dtDonHang.Rows(i)("MaSanPham")
                    newRow.Item("TenSanPham") = dtDonHang.Rows(i)("TenSanPham")
                    newRow.Item("TenQuyCach") = dtDonHang.Rows(i)("TenQuyCach")
                    newRow.Item("SoLuong") = dtDonHang.Rows(i)("SoLuong")
                    newRow.Item("DonGia") = dtDonHang.Rows(i)("DonGia")
                    'fortmatthanhtien
                    strThanhTien = CDec(dtDonHang.Rows(i)("ThanhTien")).ToString("N1", Globalization.CultureInfo.CreateSpecificCulture("en-us"))
                    newRow.Item("ThanhTien") = strThanhTien
                    newRow.Item("LoaiPhi") = dtDonHang.Rows(i)("LoaiPhi")
                    dtSanPhamHD.Rows.Add(newRow)
                Next
                'Phat Sinh Dong Trang
                Dim iRowEmpty As Integer = 15 - dtDonHang.Rows.Count - 1
                For i As Integer = 0 To iRowEmpty
                    newRow = dtSanPhamHD.NewRow
                    newRow.Item("IDSanPham") = 0
                    newRow.Item("MaSanPham") = ""
                    newRow.Item("TenSanPham") = ""
                    newRow.Item("TenQuyCach") = ""
                    newRow.Item("SoLuong") = ""
                    newRow.Item("DonGia") = ""
                    newRow.Item("ThanhTien") = ""
                    newRow.Item("LoaiPhi") = ""
                    dtSanPhamHD.Rows.Add(newRow)
                Next
                dtSanPhamHD.DefaultView.Sort = "LoaiPhi DESC"
                dgvSanPhamHopdong_Tab1.AutoGenerateColumns = False
                dgvSanPhamHopdong_Tab1.DataSource = dtSanPhamHD


                TinhTienHangChuaThue()
                TinhTienThueVAT()
                TinhTienThueDaThue()
                dbConn.Close()
                IdDonHangBan_Edit = IdDonHangBan
            Catch ex As Exception
                MessageBox.Show(ex.ToString)
            End Try
        End Sub
        Private IsViewHistory As Boolean = False

        Private Sub ExportExcel(ByVal FileName As String)
            Try
                Dim SubTitle As String
                If rbtTheoNgay.Checked Then
                    SubTitle = "Ngày " & formatDateVN2String(dtpTheoNgay.Value)
                ElseIf rbtTheoThang.Checked Then
                    Dim Thang As MonthInfo
                    Thang = CType(cbxTheoThang.SelectedItem, MonthInfo)
                    Dim Nam As YearInfo
                    Nam = CType(cbxNamTheoThang.SelectedItem, YearInfo)
                    SubTitle = " Tháng " & Thang.TenThang & " Năm " & Nam.TenNam
                ElseIf rbtTheoNam.Checked Then
                    Dim Nam As YearInfo
                    Nam = CType(cbxTheoNam.SelectedItem, YearInfo)
                    SubTitle = " Năm " & Nam.TenNam
                ElseIf rbtTuNgay.Checked Then
                    SubTitle = " Từ ngày " & formatDateVN2String(dtpTuNgay.Value) & " Đến ngày " & formatDateVN2String(dtpDenNgay.Value)
                ElseIf rbtTenKhachHang.Checked Then
                    SubTitle = "Khách hàng " & txtTenKhachHang.Text.Trim()
                ElseIf rbtSoHoaDon.Checked Then
                    SubTitle = " Hóa đơn số " & txtSoHoaDon.Text.Trim()
                End If
                Dim excelDoc As System.IO.StreamWriter = New System.IO.StreamWriter(FileName)
                Dim startExcelXML As String
                startExcelXML = "<?xml version=""1.0""?>" & vbCrLf & _
                "<?mso-application progid=""Excel.Sheet""?>" & vbCrLf & _
                "<Workbook xmlns=""urn:schemas-microsoft-com:office:spreadsheet""" & vbCrLf & _
                "xmlns:o =""urn:schemas-microsoft-com:office:office""" & vbCrLf & _
                "xmlns:x =""urn:schemas-microsoft-com:office:excel""" & vbCrLf & _
                "xmlns:ss =""urn:schemas-microsoft-com:office:spreadsheet""" & vbCrLf & _
                 "xmlns:html=""http://www.w3.org/TR/REC-html40""" & ">" & vbCrLf & _
                 "<DocumentProperties xmlns=""urn:schemas-microsoft-com:office:office""" & ">" & vbCrLf & _
                  "<LastAuthor>NG0C TRAM</LastAuthor>" & vbCrLf & _
                  "<Created>2011-04-04T13:47:34Z</Created>" & vbCrLf & _
                  "<Version>11.9999</Version>" & vbCrLf & _
                 "</DocumentProperties>" & vbCrLf & _
                 "<ExcelWorkbook xmlns=""urn:schemas-microsoft-com:office:excel""" & ">" & vbCrLf & _
                  "<WindowHeight>10005</WindowHeight>" & vbCrLf & _
                  "<WindowWidth>10005</WindowWidth>" & vbCrLf & _
                  "<WindowTopX>120</WindowTopX>" & vbCrLf & _
                  "<WindowTopY>135</WindowTopY>" & vbCrLf & _
                  "<ProtectStructure>False</ProtectStructure>" & vbCrLf & _
                  "<ProtectWindows>False</ProtectWindows>" & vbCrLf & _
                 "</ExcelWorkbook>" & vbCrLf & _
                 "<Styles>" & vbCrLf & _
                  "<Style ss:ID=""Default""" & " ss:Name=""Normal""" & ">" & vbCrLf & _
                   "<Alignment ss:Vertical=""Bottom""" & "/>" & vbCrLf & _
                   "<Borders/>" & vbCrLf & _
                   "<Font/>" & vbCrLf & _
                   "<Interior/>" & vbCrLf & _
                   "<NumberFormat/>" & vbCrLf & _
                   "<Protection/>" & vbCrLf & _
                  "</Style>" & vbCrLf & _
                  "<Style ss:ID=""s22""" & ">" & vbCrLf & _
                   "<Alignment ss:Horizontal=""Center""" & " ss:Vertical=""" & "Bottom""" & "/>" & vbCrLf & _
                   "<Font x:Family=""Swiss""" & " ss:Size=""" & "16""" & " ss:Color=""" & "#FF0000""" & " ss:Bold=""" & "1""" & "/>" & vbCrLf & _
                  "</Style>" & vbCrLf & _
                  "<Style ss:ID=""" & "s24""" & ">" & vbCrLf & _
                   "<Alignment ss:Horizontal=""Center""" & " ss:Vertical=""" & "Bottom""" & "/>" & vbCrLf & _
                   "<Font x:Family=""Swiss""" & " ss:Color=""" & "#FF0000""" & " ss:Bold=""" & "1""" & "/>" & vbCrLf & _
                  "</Style>" & vbCrLf & _
                  "<Style ss:ID=""" & "s27""" & ">" & vbCrLf & _
                   "<Font x:Family=""" & "Swiss""" & " ss:Bold=""" & "1""" & "/>" & vbCrLf & _
                   "<Interior ss:Color=""" & "#99CCFF""" & " ss:Pattern=""" & "Solid""" & "/>" & vbCrLf & _
                  "</Style>" & vbCrLf & _
                  "<Style ss:ID=""" & "s29""" & ">" & vbCrLf & _
                   "<Alignment ss:Vertical=""" & "Bottom""" & "/>" & vbCrLf & _
                  "</Style>" & vbCrLf & _
                    "<Style ss:ID=""" & "s30""" & ">" & vbCrLf & _
                    "<Alignment ss:Horizontal=""" & "Left""" & " ss:Vertical=""" & "Bottom""" & "/>" & vbCrLf & _
                    "<Font x:Family=""" & "Swiss""" & " ss:Bold=""" & "1""" & "/>" & vbCrLf & _
                    "<Interior ss:Color=""" & "#CCFFCC""" & " ss:Pattern=""" & "Solid""" & "/>" & vbCrLf & _
                    "</Style>" & vbCrLf & _
                  "<Style ss:ID=""" & "s31""" & ">" & vbCrLf & _
                   "<Alignment ss:Horizontal=""" & "Left""" & " ss:Vertical=""" & "Bottom""" & "/>" & vbCrLf & _
                   "</Style>" & vbCrLf & _
                  "<Style ss:ID=""" & "s33""" & ">" & vbCrLf & _
                   "<Alignment ss:Horizontal=""" & "Right""" & " ss:Vertical=""" & "Bottom""" & "/>" & vbCrLf & _
                   "</Style>" & vbCrLf & _
                  "<Style ss:ID=""" & "s32""" & ">" & vbCrLf & _
                  "<Alignment ss:Horizontal=""" & "Center""" & " ss:Vertical=""" & "Bottom""" & "/>" & vbCrLf & _
                  "</Style>" & vbCrLf & _
                 "</Styles>" & vbCrLf & _
                 "<Worksheet ss:Name=""" & "Sheet1""" & ">" & vbCrLf & _
                  "<Table>" & vbCrLf & _
                   "<Column ss:AutoFitWidth=""" & "0""" & " ss:Width=""" & "98.25""" & "/>" & vbCrLf & _
                   "<Column ss:AutoFitWidth=""" & "0""" & " ss:Width=""" & "99.75""" & "/>" & vbCrLf & _
                   "<Column ss:AutoFitWidth=""" & "0""" & " ss:Width=""" & "149.25""" & "/>" & vbCrLf & _
                   "<Column ss:AutoFitWidth=""" & "0""" & " ss:Width=""" & "101.25""" & "/>" & vbCrLf & _
                   "<Column ss:AutoFitWidth=""" & "0""" & " ss:Width=""" & "106.5""" & "/>" & vbCrLf & _
                   "<Column ss:AutoFitWidth=""" & "0""" & " ss:Width=""" & "93.75""" & "/>" & vbCrLf & _
                   "<Column ss:Width=""" & "72""" & "/>" & vbCrLf & _
                   "<Column ss:Width=""" & "93.75""" & "/>" & vbCrLf & _
                   "<Column ss:Width=""" & "50.25""" & "/>" & vbCrLf & _
                   "<Column ss:Width=""" & "69""" & "/>" & vbCrLf & _
                   "<Column ss:AutoFitWidth=""" & "0""" & " ss:Width=""" & "84.75""" & "/>" & vbCrLf & _
                   "<Row ss:AutoFitHeight=""" & "0""" & " ss:Height=""" & "24""" & ">" & vbCrLf & _
                    "<Cell ss:MergeAcross=""" & "5""" & " ss:StyleID=""" & "s22""" & "><Data ss:Type=""" & "String""" & ">BÁO CÁO THỐNG KÊ DOANH THU KHÁCH HÀNG</Data></Cell>" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s31""" & "/>" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s31""" & "/>" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s31""" & "/>" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s31""" & "/>" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s31""" & "/>" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s31""" & "/>" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s31""" & "/>" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s31""" & "/>" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s31""" & "/>" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s31""" & "/>" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s31""" & "/>" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s31""" & "/>" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s31""" & "/>" & vbCrLf & _
                   "</Row>" & vbCrLf & _
                   "<Row ss:Height=""" & "20.25""" & ">" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s31""" & "/>" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s31""" & "/>" & vbCrLf & _
                    "<Cell ss:MergeAcross=""" & "1""" & " ss:StyleID=""" & "s24""" & "><Data ss:Type=""" & "String""" & ">" & SubTitle & "</Data></Cell>" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s31""" & "/>" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s31""" & "/>" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s31""" & "/>" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s31""" & "/>" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s31""" & "/>" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s31""" & "/>" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s31""" & "/>" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s31""" & "/>" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s31""" & "/>" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s31""" & "/>" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s31""" & "/>" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s31""" & "/>" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s31""" & "/>" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s31""" & "/>" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s31""" & "/>" & vbCrLf & _
                   "</Row>" & vbCrLf & _
                   "<Row>" & vbCrLf & _
                    "<Cell ss:Index=""" & "4""" & " ss:StyleID=""" & "s33""" & "/>" & vbCrLf & _
                    "<Cell ss:Index=""" & "9""" & " ss:StyleID=""" & "s33""" & "/>" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s33""" & "/>" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s33""" & "/>" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s33""" & "/>" & vbCrLf & _
                   "</Row>" & vbCrLf & _
                   "<Row ss:Index=""" & "6""" & ">" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s27""" & "><Data ss:Type=""" & "String""" & ">TÊN KHÁCH HÀNG</Data></Cell>" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s27""" & "><Data ss:Type=""" & "String""" & ">MÃ SỐ THUẾ</Data></Cell>" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s27""" & "><Data ss:Type=""" & "String""" & ">ĐỊA CHỈ</Data></Cell>" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s27""" & "><Data ss:Type=""" & "String""" & ">NGÀY BÁN</Data></Cell>" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s27""" & "><Data ss:Type=""" & "String""" & ">SỐ HÓA ĐƠN</Data></Cell>" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s27""" & "><Data ss:Type=""" & "String""" & ">DOANH SỐ </Data></Cell>" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s27""" & "><Data ss:Type=""" & "String""" & ">ĐẠI LÝ TIẾP THỊ </Data></Cell>" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s29""" & "/>" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s29""" & "/>" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s29""" & "/>" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s29""" & "/>" & vbCrLf & _
                    "<Cell ss:StyleID=""" & "s29""" & "/>" & vbCrLf & _
                   "</Row>"
                Dim contentExcelXML As String = ""
                Dim dtKhachHangInfo As New DataTable
                Dim dbConn As New OleDb.OleDbConnection
                Dim dataAccess As New DataAccess
                Dim dbCommand As OleDb.OleDbCommand
                dataAccess.ConnectDatabase_DBAccess(dbConn)
                Dim ThongTin As String
                Dim IDKhachHang As Integer
                For i As Integer = 0 To dgvKhachHang.RowCount - 1
                    'check DaiLyTiepThi
                    IDKhachHang = Integer.Parse(dgvKhachHang(0, i).Value)
                    dbCommand = New OleDbCommand("spThongTinTiepThi", dbConn)
                    dbCommand.CommandType = CommandType.StoredProcedure
                    dbCommand.Parameters.Add("@IDDonHangBan", OleDbType.Integer).Value = IDKhachHang
                    ThongTin = dbCommand.ExecuteScalar().ToString()
                    contentExcelXML = contentExcelXML & "<Row>" & vbCrLf & _
                "<Cell ss:StyleID=""" & "s31""" & "><Data ss:Type=""" & "String""" & ">" & dgvKhachHang(3, i).Value & "</Data></Cell>" & vbCrLf & _
                "<Cell ss:StyleID=""" & "s31""" & "><Data ss:Type=""" & "String""" & ">" & dgvKhachHang(4, i).Value & "</Data></Cell>" & vbCrLf & _
                "<Cell ss:StyleID=""" & "s31""" & "><Data ss:Type=""" & "String""" & ">" & dgvKhachHang(5, i).Value & "</Data></Cell>" & vbCrLf & _
                "<Cell ss:StyleID=""" & "s32""" & "><Data ss:Type=""" & "String""" & ">" & dgvKhachHang(6, i).Value & "</Data></Cell>" & vbCrLf & _
                "<Cell ss:StyleID=""" & "s32""" & "><Data ss:Type=""" & "String""" & ">" & dgvKhachHang(2, i).Value & "</Data></Cell>" & vbCrLf & _
                "<Cell ss:StyleID=""" & "s33""" & "><Data ss:Type=""" & "String""" & ">" & dgvKhachHang(7, i).Value & "</Data></Cell>" & vbCrLf & _
                "<Cell ss:StyleID=""" & "s31""" & "><Data ss:Type=""" & "String""" & ">" & ThongTin & "</Data></Cell>" & vbCrLf & _
                "<Cell ss:StyleID=""" & "s29""" & "/>" & vbCrLf & _
                "<Cell ss:StyleID=""" & "s29""" & "/>" & vbCrLf & _
                "<Cell ss:StyleID=""" & "s29""" & "/>" & vbCrLf & _
                "<Cell ss:StyleID=""" & "s29""" & "/>" & vbCrLf & _
               "</Row>"
                    'End If
                Next
                dbConn.Close()
                Dim endExcelXML As String
                endExcelXML = "</Table>" & vbCrLf & _
                  "<WorksheetOptions xmlns=""" & "urn:schemas-microsoft-com:office:excel""" & ">" & vbCrLf & _
                   "<Print>" & vbCrLf & _
                    "<ValidPrinterInfo/>" & vbCrLf & _
                    "<PaperSizeIndex>0</PaperSizeIndex>" & vbCrLf & _
                    "<HorizontalResolution>600</HorizontalResolution>" & vbCrLf & _
                    "<VerticalResolution>600</VerticalResolution>" & vbCrLf & _
                   "</Print>" & vbCrLf & _
                   "<Selected/>" & vbCrLf & _
                   "<Panes>" & vbCrLf & _
                    "<Pane>" & vbCrLf & _
                     "<Number>3</Number>" & vbCrLf & _
                     "<ActiveRow>1</ActiveRow>" & vbCrLf & _
                     "<ActiveCol>2</ActiveCol>" & vbCrLf & _
                     "<RangeSelection>R2C3:R2C4</RangeSelection>" & vbCrLf & _
                    "</Pane>" & vbCrLf & _
                   "</Panes>" & vbCrLf & _
                   "<ProtectObjects>False</ProtectObjects>" & vbCrLf & _
                   "<ProtectScenarios>False</ProtectScenarios>" & vbCrLf & _
                  "</WorksheetOptions>" & vbCrLf & _
                 "</Worksheet>" & vbCrLf & _
                "</Workbook>"
                excelDoc.Write(startExcelXML & contentExcelXML & endExcelXML)
                excelDoc.Close()
            Catch ex As Exception

            End Try
        End Sub
        Private Sub cemConvertExcel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cemConvertExcel.Click
            Try
                frmSaveFile.FileType = ".xls"
                ShowModalForm(frmSaveFile, False, False)
                Dim result As Boolean
                result = frmSaveFile.Result
                If result Then
                    Dim Path As String = frmSaveFile.Path
                    Dim FileName As String = frmSaveFile.FileName
                    ExportExcel(Path & "/" & FileName & ".xls")
                End If
                frmSaveFile.txtPath.Text = ""
                frmSaveFile.txtFile.Text = ""
            Catch ex As Exception

            End Try
        End Sub
        Private Sub dgvSanPhamHopdong_Tab1_DataError(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewDataErrorEventArgs) Handles dgvSanPhamHopdong_Tab1.DataError

        End Sub

        Private Sub txtSo_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtSo.Leave
            Try
                Dim KetQua As Integer
                Dim dbConn As New OleDb.OleDbConnection
                Dim dataAccess As New DataAccess
                dataAccess.ConnectDatabase_DBAccess(dbConn)
                Using dbConn
                    Dim dbCommand As OleDb.OleDbCommand
                    dbCommand = New OleDbCommand("spKiemTraSoHoaDon", dbConn)
                    dbCommand.CommandType = CommandType.StoredProcedure
                    dbCommand.Parameters.Add("@So", OleDbType.Integer).Value = Integer.Parse(txtSo.Text)
                    KetQua = dbCommand.ExecuteScalar()
                    dbConn.Close()
                End Using
                If KetQua = 1 Then
                    Dim dglResult As DialogResult
                    'dglResult = MessageBox.Show("Số hóa đơn này đã được nhập.Vui lòng kiểm tra lại.", "Thông báo", MessageBoxButtons.OKCancel)
                    dglResult = SDNMessageBox("Số hóa đơn này đã được nhập.Vui lòng kiểm tra lại", "Thông báo", MessageBoxButtons.OKCancel, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1)
                    If dglResult = Windows.Forms.DialogResult.OK Then
                        txtSo.Focus()
                    ElseIf dglResult = Windows.Forms.DialogResult.Cancel Then
                        txtHoTenNguoiMua.Focus()
                    End If
                End If
            Catch ex As Exception

            End Try
        End Sub

        Private Sub cbxEditVat_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbxEditVat.CheckedChanged
            Try
                If cbxEditVat.Checked Then
                    txtVat.Enabled = True
                Else
                    txtVat.Enabled = False
                End If
            Catch ex As Exception

            End Try
        End Sub

        Private Sub txtMaKhachHang_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtMaKhachHang.KeyDown
            Try
                If e.KeyCode = Keys.Enter Then
                    'Truyen MaKhachHang De Lay Thong Tin
                    Dim dtKhachHangInfo As New DataTable
                    Dim dbConn As New OleDb.OleDbConnection
                    Dim dataAccess As New DataAccess
                    Dim adapter As OleDb.OleDbDataAdapter
                    Dim dbCommand As OleDb.OleDbCommand
                    dataAccess.ConnectDatabase_DBAccess(dbConn)
                    dbCommand = New OleDbCommand("spKhachHang_Item", dbConn)
                    dbCommand.CommandType = CommandType.StoredProcedure
                    dbCommand.Parameters.Add("@KhachHangId", OleDbType.Integer).Value = 0
                    dbCommand.Parameters.Add("@CodeKhachHang", OleDbType.VarWChar).Value = txtMaKhachHang.Text.Trim
                    dbCommand.Parameters.Add("@Type", OleDbType.Integer).Value = 1
                    adapter = New OleDb.OleDbDataAdapter(dbCommand)
                    adapter.Fill(dtKhachHangInfo)
                    dbConn.Close()
                    If dtKhachHangInfo.Rows.Count > 0 Then
                        lblKhachHangId.Text = dtKhachHangInfo.Rows(0)("KhachHangId")
                        txtMaKhachHang.Text = IIf(IsDBNull(dtKhachHangInfo.Rows(0)("CodeKhachHang")), "", dtKhachHangInfo.Rows(0)("CodeKhachHang"))
                        txtTenKhachHang.Text = IIf(IsDBNull(dtKhachHangInfo.Rows(0)("TenKhachHang")), "", dtKhachHangInfo.Rows(0)("TenKhachHang"))
                        txtDiaChi.Text = dtKhachHangInfo.Rows(0)("DiaChi")
                        txtMaSoThue.Text = IIf(IsDBNull(dtKhachHangInfo.Rows(0)("MaSoThue")), "", dtKhachHangInfo.Rows(0)("MaSoThue"))
                        cbxNhanVienTT.SelectedValue = Integer.Parse(IIf(IsDBNull(dtKhachHangInfo.Rows(0)("NhanVienTiepThiId")), 0, dtKhachHangInfo.Rows(0)("NhanVienTiepThiId").ToString))
                        Panel_KhachHang.Visible = False
                        txtHinhThucThanhToan.Focus()
                    Else
                        txtMaKhachHang.Focus()
                    End If
                End If
            Catch ex As Exception

            End Try
        End Sub

        Private Sub cmdKhoiPhuc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdKhoiPhuc.Click
            Dim IDDonHangBan As Integer = Integer.Parse(dgvKhachHang.Rows(dgvKhachHang.CurrentCell.RowIndex).Cells("IDDonHangBan").Value.ToString)
            'check tình trạng, nếu đơn hàng đã duyệt thì không thể xóa

            Dim dbConn As New OleDb.OleDbConnection
            Dim dataAccess As New DataAccess
            Dim query As String
            dataAccess.ConnectDatabase_DBAccess(dbConn)
            Dim TrangThai As String = ""
            Dim dbCommand As OleDb.OleDbCommand
            query = "Select TrangThai From DonHangBan Where IdDonHangBan=" & IDDonHangBan
            dbCommand = New OleDbCommand(query, dbConn)
            TrangThai = dbCommand.ExecuteScalar()
            If TrangThai = "Đã duyệt" Then
                MessageBox.Show("Đơn hàng đã duyệt. Chỉ có đơn hàng đã hủy mới khôi phục lại.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Hand)
                dbConn.Close()
                Exit Sub
            End If
            Dim dlgRes As DialogResult
            dlgRes = MessageBox.Show( _
                      "Bạn đồng ý khôi phục đơn hàng này?", _
                      "Thông báo", _
                MessageBoxButtons.OKCancel, _
                      MessageBoxIcon.Question)
            If dlgRes = Windows.Forms.DialogResult.OK Then
                query = String.Format("Update DonHangBan Set TrangThai=N'Đã duyệt' Where IDDonHangBan={0};Update ChiTietDonHangBan Set TrangThai=N'Đã duyệt' Where IDDonHangBan={0}", IDDonHangBan)
                dbCommand = New OleDb.OleDbCommand(query, dbConn)
                dbCommand.ExecuteNonQuery()
                dbConn.Close()
                '
                Select Case ReportType
                    Case 0
                        Report_TheoNgay()
                    Case 1
                        Report_TheoThang()
                    Case 2
                        Report_TheoNam()
                    Case 3
                        Report_TuNgayDenNgay()
                    Case 4
                        Report_TenKhachHang()
                    Case 5
                        Report_SoHoaDon()
                End Select
            End If
        End Sub

        Private Sub txtMaKhachHang_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtMaKhachHang.KeyUp
            Try
                If txtMaKhachHang.Text = "" Then
                    lblKhachHangId.Text = "0"
                    txtDiaChi.Text = ""
                    txtMaSoThue.Text = ""
                    txtTenKhachHang.Text = ""
                End If
            Catch ex As Exception

            End Try
        End Sub

        Private Sub cmdXemDonHang_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdXemDonHang.Click
            Try
                Dim IDDonHangBan As Integer = Integer.Parse(dgvKhachHang.Rows(dgvKhachHang.CurrentCell.RowIndex).Cells("IDDonHangBan").Value.ToString)
                frmSuaPhiVanChuyen.IDDonHangBan = IDDonHangBan
                ShowModalForm(frmSuaPhiVanChuyen, False, False)
                frmSuaPhiVanChuyen.IDDonHangBan = 0
                'Select Case ReportType
                '    Case 0
                '        Report_TheoNgay()
                '    Case 1
                '        Report_TheoThang()
                '    Case 2
                '        Report_TheoNam()
                '    Case 3
                '        Report_TuNgayDenNgay()
                '    Case 4
                '        Report_TenKhachHang()
                '    Case 5
                '        Report_SoHoaDon()
                'End Select
            Catch ex As Exception

            End Try
        End Sub
    End Class
End Namespace
